

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" href="/blog/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="TypeScript
是 JavaScript 的类型的超集，它可以编译成纯 JavaScript。编译出来的 JavaScript 可以运行在任何浏览器上。TypeScript 编译工具可以运行在任何服务器和任何系统上。">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
  <title>typescript - Mike_Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.4.0/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"dcmaomi.gitee.io","root":"/blog/","version":"1.8.9a","typing":{"enable":true,"typeSpeed":70,"cursorChar":"|","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}}};
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>Mike_Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于我
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/blog/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="typescript">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-01-13 14:00" pubdate>
        2021年1月13日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      19.5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      260
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">typescript</h1>
            
            <div class="markdown-body">
              <h1 id="TypeScript"><a href="#TypeScript" class="headerlink" title="TypeScript"></a>TypeScript</h1><ul>
<li>是 JavaScript 的类型的超集，它可以编译成纯 JavaScript。编译出来的 JavaScript 可以运行在任何浏览器上。TypeScript 编译工具可以运行在任何服务器和任何系统上。<span id="more"></span>
<h1 id="typescript的优势"><a href="#typescript的优势" class="headerlink" title="typescript的优势"></a>typescript的优势</h1></li>
</ul>
<ol>
<li>TypeScript 增加了代码的可读性和可维护性</li>
</ol>
<ul>
<li>类型系统实际上是最好的文档，大部分的函数看看类型的定义就可以知道如何使用了</li>
<li>可以在编译阶段就发现大部分错误，这总比在运行时候出错好</li>
<li>增强了编辑器和 IDE 的功能，包括代码补全、接口提示、跳转到定义、重构等</li>
</ul>
<ol start="2">
<li>TypeScript 非常包容</li>
</ol>
<ul>
<li>TypeScript 是 JavaScript 的超集，.js 文件可以直接重命名为 .ts 即可</li>
<li>即使不显式的定义类型，也能够自动做出类型推论</li>
<li>可以定义从简单到复杂的几乎一切类型</li>
<li>即使 TypeScript 编译报错，也可以生成 JavaScript 文件</li>
<li>兼容第三方库，即使第三方库不是用 TypeScript 写的，也可以编写单独的类型文件供TypeScript 读取</li>
</ul>
<ol start="3">
<li>TypeScript 拥有活跃的社区</li>
</ol>
<ul>
<li>大部分第三方库都有提供给 TypeScript 的类型定义文件</li>
<li>Google 开发的 Angular2 就是使用 TypeScript 编写的</li>
<li>TypeScript 拥抱了 ES6 规范，也支持部分 ESNext 草案的规范<h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1>TypeScript 的命令行工具安装方法如下：<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs cmake">npm <span class="hljs-keyword">install</span> -g typescript<br>tsc hello.ts<br></code></pre></td></tr></table></figure>
以上命令会在全局环境下安装 tsc 命令，安装完成之后，我们就可以在任何地方执行 tsc 命令了。我们约定使用 TypeScript 编写的文件以 .ts 为后缀，用 TypeScript 编写 React 时，以 .tsx 为后缀。<h2 id="运行"><a href="#运行" class="headerlink" title="运行"></a>运行</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs javascript">   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">person: string</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&#x27;Hello, &#x27;</span> + person;<br>&#125;<br><br><span class="hljs-keyword">let</span> user = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><span class="hljs-built_in">console</span>.log(sayHello(user));<br></code></pre></td></tr></table></figure>
执行<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-attribute">tsc</span> hello.ts<br></code></pre></td></tr></table></figure>
这时候会生成一个编译好的文件 hello.js：<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs javascript">   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">person</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&#x27;Hello, &#x27;</span> + person;<br>&#125;<br><span class="hljs-keyword">var</span> user = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><span class="hljs-built_in">console</span>.log(sayHello(user));<br></code></pre></td></tr></table></figure>
<h1 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h1></li>
</ul>
<h2 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h2><p>  为了让程序有价值，我们需要能够处理最简单的数据单元：数字，字符串，结构体，布尔值等。 TypeScript支持与JavaScript几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。</p>
<h3 id="布尔类型"><a href="#布尔类型" class="headerlink" title="布尔类型"></a>布尔类型</h3><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> isDone: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;<br></code></pre></td></tr></table></figure>
<h3 id="数值类型"><a href="#数值类型" class="headerlink" title="数值类型"></a>数值类型</h3> <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> decLiteral: <span class="hljs-built_in">number</span> = <span class="hljs-number">6</span>;<br><span class="hljs-keyword">let</span> hexLiteral: <span class="hljs-built_in">number</span> = <span class="hljs-number">0xf00d</span>;<br><span class="hljs-keyword">let</span> binaryLiteral: <span class="hljs-built_in">number</span> = <span class="hljs-number">0b1010</span>;<br><span class="hljs-keyword">let</span> octalLiteral: <span class="hljs-built_in">number</span> = <span class="hljs-number">0o744</span>;<br></code></pre></td></tr></table></figure>
<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><p>   像其它语言里一样，我们使用string表示文本数据类型。 和JavaScript一样，可以使用双引号（”）或单引号（’）表示字符串。<br>   <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs typescript">   <span class="hljs-keyword">let</span> name: <span class="hljs-built_in">string</span> = <span class="hljs-string">&quot;bob&quot;</span>;<br>name = <span class="hljs-string">&quot;smith&quot;</span><br></code></pre></td></tr></table></figure><br>   你还可以使用模版字符串，它可以定义多行文本和内嵌表达式。 这种字符串是被反引号</p>
<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><p>   TypeScript像JavaScript一样可以操作数组元素。 有两种方式可以定义数组。 第一种，可以在元素类型后面接上[]，表示由此类型元素组成的一个数组</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> list: <span class="hljs-built_in">number</span>[] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];<br></code></pre></td></tr></table></figure>
<p>第二种方式是使用数组泛型，Array&lt;元素类型&gt;：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> list: <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">number</span>&gt; = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];<br></code></pre></td></tr></table></figure>
<h3 id="元组-Tuple"><a href="#元组-Tuple" class="headerlink" title="元组 Tuple"></a>元组 Tuple</h3> <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// Declare a tuple type</span><br><span class="hljs-keyword">let</span> x: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br><span class="hljs-comment">// Initialize it</span><br>x = [<span class="hljs-string">&#x27;hello&#x27;</span>, <span class="hljs-number">10</span>]; <span class="hljs-comment">// OK</span><br><span class="hljs-comment">// Initialize it incorrectly</span><br>x = [<span class="hljs-number">10</span>, <span class="hljs-string">&#x27;hello&#x27;</span>]; <span class="hljs-comment">// Error</span><br></code></pre></td></tr></table></figure>
<p>当访问一个已知索引的元素，会得到正确的类型：<br> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-built_in">console</span>.log(x[<span class="hljs-number">0</span>].substr(<span class="hljs-number">1</span>)); <span class="hljs-comment">// OK</span><br><span class="hljs-built_in">console</span>.log(x[<span class="hljs-number">1</span>].substr(<span class="hljs-number">1</span>)); <span class="hljs-comment">// Error, &#x27;number&#x27; does not have &#x27;substr&#x27;</span><br></code></pre></td></tr></table></figure><br>当访问一个越界的元素，会使用联合类型替代：<br> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript">x[<span class="hljs-number">3</span>] = <span class="hljs-string">&#x27;world&#x27;</span>; <span class="hljs-comment">// OK, 字符串可以赋值给(string | number)类型</span><br><span class="hljs-built_in">console</span>.log(x[<span class="hljs-number">5</span>].toString()); <span class="hljs-comment">// OK, &#x27;string&#x27; 和 &#x27;number&#x27; 都有 toString</span><br>x[<span class="hljs-number">6</span>] = <span class="hljs-literal">true</span>; <span class="hljs-comment">// Error, 布尔不是(string | number)类型</span><br></code></pre></td></tr></table></figure></p>
<h3 id="枚举"><a href="#枚举" class="headerlink" title="枚举"></a>枚举</h3><p> enum类型是对JavaScript标准数据类型的一个补充。 像C#等其它语言一样，使用枚举类型可以为一组数值赋予友好的名字。</p>
 <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-built_in">enum</span> Color &#123;Red, Green, Blue&#125;<br><span class="hljs-keyword">let</span> c: Color = Color.Green;<br></code></pre></td></tr></table></figure>
<p>上述代码编译为JS之后是这样的：</p>
 <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> Color;<br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Color</span>) </span>&#123;<br>    Color[Color[<span class="hljs-string">&quot;Red&quot;</span>] = <span class="hljs-number">0</span>] = <span class="hljs-string">&quot;Red&quot;</span>;<br>    Color[Color[<span class="hljs-string">&quot;Green&quot;</span>] = <span class="hljs-number">1</span>] = <span class="hljs-string">&quot;Green&quot;</span>;<br>    Color[Color[<span class="hljs-string">&quot;Blue&quot;</span>] = <span class="hljs-number">2</span>] = <span class="hljs-string">&quot;Blue&quot;</span>;<br>&#125;)(Color || (Color = &#123;&#125;));<br><span class="hljs-keyword">var</span> c = Color.Green;<br><span class="hljs-built_in">console</span>.log(Color)<br><span class="hljs-comment">//&#123; &#x27;0&#x27;: &#x27;Red&#x27;, &#x27;1&#x27;: &#x27;Green&#x27;, &#x27;2&#x27;: &#x27;Blue&#x27;, Red: 0, Green: 1, Blue: 2 &#125;</span><br></code></pre></td></tr></table></figure>
<p>默认情况下，从0开始为元素编号。 你也可以手动的指定成员的数值。 例如，我们将上面的例子改成从1开始编号：<br> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">var</span> Color;<br>num Color &#123;Red = <span class="hljs-number">1</span>, Green, Blue&#125;<br><span class="hljs-keyword">let</span> c: Color = Color.Green;<br></code></pre></td></tr></table></figure><br>枚举类型提供的一个便利是你可以由枚举的值得到它的名字。 例如，我们知道数值为2，但是不确定它映射到Color里的哪个名字，我们可以查找相应的名字：<br> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript">enum Color &#123;Red = <span class="hljs-number">1</span>, Green, Blue&#125;<br><span class="hljs-keyword">let</span> colorName: string = Color[<span class="hljs-number">2</span>];<br><span class="hljs-built_in">console</span>.log(colorName); <br></code></pre></td></tr></table></figure></p>
<h3 id="任意值"><a href="#任意值" class="headerlink" title="任意值"></a>任意值</h3><p> 有时候，我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容，比如来自用户输入或第三方代码库。 这种情况下，我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用any类型来标记这些变量<br> <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> notSure: <span class="hljs-built_in">any</span> = <span class="hljs-number">4</span>;<br>notSure = <span class="hljs-string">&quot;maybe a string instead&quot;</span>;<br>notSure = <span class="hljs-literal">false</span>; <span class="hljs-comment">// okay, definitely a boolean</span><br></code></pre></td></tr></table></figure><br>在对现有代码进行改写的时候，any类型是十分有用的，它允许你在编译时可选择地包含或移除类型检查。 你可能认为Object有相似的作用，就像它在其它语言中那样。 但是Object类型的变量只是允许你给它赋任意值 - 但是却不能够在它上面调用任意的方法，即便它真的有这些方法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> notSure: <span class="hljs-built_in">any</span> = <span class="hljs-number">4</span>;<br>notSure.ifItExists(); <span class="hljs-comment">// okay, ifItExists might exist at runtime</span><br>notSure.toFixed(); <span class="hljs-comment">// okay, toFixed exists (but the compiler doesn&#x27;t check)</span><br><br><span class="hljs-keyword">let</span> prettySure: <span class="hljs-built_in">Object</span> = <span class="hljs-number">4</span>;<br>prettySure.toFixed(); <span class="hljs-comment">// Error: Property &#x27;toFixed&#x27; doesn&#x27;t exist on type &#x27;Object&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>当你只知道一部分数据的类型时，any类型也是有用的。 比如，你有一个数组，它包含了不同的类型的数据：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> list: <span class="hljs-built_in">any</span>[] = [<span class="hljs-number">1</span>, <span class="hljs-literal">true</span>, <span class="hljs-string">&quot;free&quot;</span>];<br><br>list[<span class="hljs-number">1</span>] = <span class="hljs-number">100</span>;<br></code></pre></td></tr></table></figure>
<h3 id="空值"><a href="#空值" class="headerlink" title="空值"></a>空值</h3><p> 某种程度上来说，void类型像是与any类型相反，它表示没有任何类型。 当一个函数没有返回值时，你通常会见到其返回值类型是void：<br> <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">warnUser</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span> </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&quot;This is my warning message&quot;</span>);<br>&#125;<br></code></pre></td></tr></table></figure><br> 声明一个void类型的变量没有什么大用，因为你只能为它赋予undefined和null：<br>  <figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> unusable: <span class="hljs-built_in">void</span> = <span class="hljs-literal">undefined</span><br></code></pre></td></tr></table></figure></p>
<h3 id="对象的类型——接口"><a href="#对象的类型——接口" class="headerlink" title="对象的类型——接口"></a>对象的类型——接口</h3><ul>
<li>在 TypeScript 中，我们使用接口<strong>（Interfaces）</strong>来定义对象的类型。<br>什么是接口：</li>
<li>在面向对象语言中，接口（Interfaces）是一个很重要的概念，它是对行为的抽象，而具体如何行动需要由类（classes）去实现（implement）。</li>
<li>TypeScript 中的接口是一个非常灵活的概念，除了可用于对类的一部分行为进行抽象以外，也常用于对「对象的形状（Shape）」进行描述。<br>例子：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span><br>&#125;;<br></code></pre></td></tr></table></figure></li>
<li>上面的例子中，我们定义了一个接口 Person，接着定义了一个变量 tom，它的类型是 Person。这样，我们就约束了 tom 的形状必须和接口 Person 一致。</li>
<li>接口一般首字母大写。有的编程语言中会建议接口的名称加上I前缀。</li>
<li>定义的变量比接口少了一些属性是不允许的：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span><br>&#125;;<br><br><span class="hljs-comment">// index.ts(6,5): error TS2322: Type &#x27;&#123; name: string; &#125;&#x27; is not assignable to type &#x27;Person&#x27;.</span><br><span class="hljs-comment">//   Property &#x27;age&#x27; is missing in type &#x27;&#123; name: string; &#125;&#x27;.</span><br></code></pre></td></tr></table></figure></li>
<li>多一些属性也是不允许的：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br><br><span class="hljs-comment">// index.ts(9,5): error TS2322: Type &#x27;&#123; name: string; age: number; gender: string; &#125;&#x27; is not assignable to type &#x27;Person&#x27;.</span><br><span class="hljs-comment">//   Object literal may only specify known properties, and &#x27;gender&#x27; does not exist in type &#x27;Person&#x27;.</span><br></code></pre></td></tr></table></figure></li>
<li>可见，赋值的时候，变量的形状必须和接口的形状保持一致。<h3 id="可选属性"><a href="#可选属性" class="headerlink" title="可选属性"></a>可选属性</h3><ul>
<li>有时我们希望不要完全匹配一个形状，那么可以用可选属性<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span><br>&#125;;<br><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span><br>&#125;;<br></code></pre></td></tr></table></figure></li>
</ul>
</li>
<li>可选属性的含义是该属性可以不存在。<br>这时仍然不允许添加未定义的属性：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br></code></pre></td></tr></table></figure></li>
<li>任意属性：</br><br>有时候我们希望一个接口允许有任意的属性，可以使用如下方式：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs typescript">  <span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>    [propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br></code></pre></td></tr></table></figure>
使用 [propName: string] 定义了任意属性取 string 类型的值。</br><br>需要注意的是，一旦定义了任意属性，那么确定属性和可选属性的类型都必须是它的类型的子集：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript">   <span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>    [propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br><br><span class="hljs-comment">// index.ts(3,5): error TS2411: Property &#x27;age&#x27; of type &#x27;number&#x27; is not assignable to string index type &#x27;string&#x27;.</span><br><span class="hljs-comment">// index.ts(7,5): error TS2322: Type &#x27;&#123; [x: string]: string | number; name: string; age: number; gender: string; &#125;&#x27; is not assignable to type &#x27;Person&#x27;.</span><br><span class="hljs-comment">//   Index signatures are incompatible.</span><br><span class="hljs-comment">//     Type &#x27;string | number&#x27; is not assignable to type &#x27;string&#x27;.</span><br><span class="hljs-comment">//       Type &#x27;number&#x27; is not assignable to type &#x27;string&#x27;.</span><br></code></pre></td></tr></table></figure>
上例中，任意属性的值允许是 string，但是可选属性 age 的值却是 number，number 不是 string 的子属性，所以报错了。<br><br>另外，在报错信息中可以看出，此时 { name: ‘Tom’, age: 25, gender: ‘male’ } 的类型被推断成了 { [x: string]: string | number; name: string; age: number; gender: string; }，这是联合类型和接口的结合。<br><br>一个接口中只能定义一个任意属性。如果接口中有多个类型的属性，则可以在任意属性中使用联合类型<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> Person &#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>    [propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    age: <span class="hljs-number">25</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br></code></pre></td></tr></table></figure></li>
<li>只读属性<br><br>有时候我们希望对象中的一些字段只能在创建的时候被赋值，那么可以用 readonly 定义只读属性：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs typescript"> <span class="hljs-keyword">interface</span> Person &#123;<br>    <span class="hljs-keyword">readonly</span> id: <span class="hljs-built_in">number</span>;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>    [propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    id: <span class="hljs-number">89757</span>,<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br><br>tom.id = <span class="hljs-number">9527</span>;<br><br><span class="hljs-comment">// index.ts(14,5): error TS2540: Cannot assign to &#x27;id&#x27; because it is a constant or a read-only property.</span><br></code></pre></td></tr></table></figure>
上例中，使用 readonly 定义的属性 id 初始化后，又被赋值了，所以报错了。<br><blockquote>
<p>注意，只读的约束存在于第一次给对象赋值的时候，而不是第一次给只读属性赋值的时候，只读属性不能是可选属性，初始化的时候必须带有该属性</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript"> <span class="hljs-keyword">interface</span> Person &#123;<br>    <span class="hljs-keyword">readonly</span> id: <span class="hljs-built_in">number</span>;<br>    name: <span class="hljs-built_in">string</span>;<br>    age?: <span class="hljs-built_in">number</span>;<br>    [propName: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> tom: Person = &#123;<br>    name: <span class="hljs-string">&#x27;Tom&#x27;</span>,<br>    gender: <span class="hljs-string">&#x27;male&#x27;</span><br>&#125;;<br><br>tom.id = <span class="hljs-number">89757</span>;<br><br><span class="hljs-comment">// index.ts(8,5): error TS2322: Type &#x27;&#123; name: string; gender: string; &#125;&#x27; is not assignable to type &#x27;Person&#x27;.</span><br><span class="hljs-comment">//   Property &#x27;id&#x27; is missing in type &#x27;&#123; name: string; gender: string; &#125;&#x27;.</span><br><span class="hljs-comment">// index.ts(13,5): error TS2540: Cannot assign to &#x27;id&#x27; because it is a constant or a read-only property.</span><br></code></pre></td></tr></table></figure>
上例中，报错信息有两处，第一处是在对 tom 进行赋值的时候，没有给 id 赋值。</li>
</ul>
<p>第二处是在给 tom.id 赋值的时候，由于它是只读属性，所以报错了。</p>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><ul>
<li><p>函数声明：<br><br>众所周知，在 JavaScript 中，有两种常见的定义函数的方式——函数声明（Function Declaration）和函数表达式（Function Expression）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript">  <span class="hljs-comment">// 函数声明（Function Declaration）</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x, y</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;<br><br><span class="hljs-comment">// 函数表达式（Function Expression）</span><br><span class="hljs-keyword">let</span> mySum = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x, y</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;;<br></code></pre></td></tr></table></figure>
<p>一个函数有输入和输出，要在 TypeScript 中对其进行约束，需要把输入和输出都考虑到，其中函数声明的类型定义较简单：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>注意，输入多余的（或者少于要求的）参数，是不被允许的：</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs typescript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;<br>sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);<br><br><span class="hljs-comment">// index.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target.</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;<br>sum(<span class="hljs-number">1</span>);<br><span class="hljs-comment">// index.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target</span><br></code></pre></td></tr></table></figure>
<ul>
<li>函数表达式 <br><br>如果要我们现在写一个对函数表达式（Function Expression）的定义，可能会写成这样：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript">  <span class="hljs-keyword">let</span> mySum = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;<br></code></pre></td></tr></table></figure>
这是可以通过编译的，不过事实上，上面的代码只对等号右侧的匿名函数进行了类型定义，而等号左边的 mySum，是通过赋值操作进行类型推论而推断出来的。如果需要我们手动给 mySum 添加类型，则应该是这样：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> mySum: <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>) =&gt;</span> <span class="hljs-built_in">number</span> = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> x + y;<br>&#125;;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>注意不要混淆了 TypeScript 中的 =&gt;和 ES6 中的 =&gt;。在 TypeScript 的类型定义中，=&gt;用来表示函数的定义，左边是输入类型，需要用括号括起来，右边是输出类型。在 ES6 中，=&gt;叫做箭头函数，应用十分广泛，可以参考 ES6 中的箭头函数。</p>
</blockquote>
</li>
</ul>
</li>
<li><p>用接口定义函数的形状：</p>
<p>我们也可以使用接口的方式来定义一个函数需要符合的形状</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> SearchFunc &#123;<br>    (source: <span class="hljs-built_in">string</span>, <span class="hljs-attr">subString</span>: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">boolean</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> mySearch: SearchFunc;<br>mySearch = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">source: <span class="hljs-built_in">string</span>, subString: <span class="hljs-built_in">string</span></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> source.search(subString) !== -<span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>采用函数表达式|接口定义函数的方式时，对等号左侧进行类型限制，可以保证以后对函数名赋值时保证参数个数、参数类型、返回值类型不变。</p>
</li>
<li><p>可选参数：</p>
<p> 前面提到，输入多余的（或者少于要求的）参数，是不允许的。那么如何定义可选的参数呢？</p>
<p> 与接口中的可选属性类似，我们用 ? 表示可选的参数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript">    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buildName</span>(<span class="hljs-params">firstName: <span class="hljs-built_in">string</span>, lastName?: <span class="hljs-built_in">string</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span> (lastName) &#123;<br>        <span class="hljs-keyword">return</span> firstName + <span class="hljs-string">&#x27; &#x27;</span> + lastName;<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-keyword">return</span> firstName;<br>    &#125;<br>&#125;<br><span class="hljs-keyword">let</span> tomcat = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-string">&#x27;Cat&#x27;</span>);<br><span class="hljs-keyword">let</span> tom = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>需要注意的是，可选参数必须接在必需参数后面。换句话说，可选参数后面不允许再出现必需参数了：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buildName</span>(<span class="hljs-params">firstName?: <span class="hljs-built_in">string</span>, lastName: <span class="hljs-built_in">string</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span> (firstName) &#123;<br>        <span class="hljs-keyword">return</span> firstName + <span class="hljs-string">&#x27; &#x27;</span> + lastName;<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-keyword">return</span> lastName;<br>    &#125;<br>&#125;<br><span class="hljs-keyword">let</span> tomcat = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-string">&#x27;Cat&#x27;</span>);<br><span class="hljs-keyword">let</span> tom = buildName(<span class="hljs-literal">undefined</span>, <span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure></li>
<li><p>参数默认值</p>
<p>  在 ES6 中，我们允许给函数的参数添加默认值，TypeScript 会将添加了默认值的参数识别为可选参数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buildName</span>(<span class="hljs-params">firstName: <span class="hljs-built_in">string</span>, lastName: <span class="hljs-built_in">string</span> = <span class="hljs-string">&#x27;Cat&#x27;</span></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> firstName + <span class="hljs-string">&#x27; &#x27;</span> + lastName;<br>&#125;<br><span class="hljs-keyword">let</span> tomcat = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-string">&#x27;Cat&#x27;</span>);<br><span class="hljs-keyword">let</span> tom = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>此时就不受「可选参数必须接在必需参数后面」的限制了：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buildName</span>(<span class="hljs-params">firstName: <span class="hljs-built_in">string</span> = <span class="hljs-string">&#x27;Tom&#x27;</span>, lastName: <span class="hljs-built_in">string</span></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> firstName + <span class="hljs-string">&#x27; &#x27;</span> + lastName;<br>&#125;<br><span class="hljs-keyword">let</span> tomcat = buildName(<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-string">&#x27;Cat&#x27;</span>);<br><span class="hljs-keyword">let</span> cat = buildName(<span class="hljs-literal">undefined</span>, <span class="hljs-string">&#x27;Cat&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>关于默认参数，可以参考 ES6 中函数参数的默认值。</p>
</li>
<li><p>剩余参数</p>
<p>ES6 中，可以使用 …rest 的方式获取函数中的剩余参数（rest 参数）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript">   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">push</span>(<span class="hljs-params">array, ...items</span>) </span>&#123;<br>    items.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>) </span>&#123;<br>        array.push(item);<br>    &#125;);<br>&#125;<br><span class="hljs-keyword">let</span> a: any[] = [];<br>push(a, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);<br></code></pre></td></tr></table></figure>
<p>事实上，items 是一个数组。所以我们可以用数组的类型来定义它</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">push</span>(<span class="hljs-params">array: <span class="hljs-built_in">any</span>[], ...items: <span class="hljs-built_in">any</span>[]</span>) </span>&#123;<br>    items.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>) </span>&#123;<br>        array.push(item);<br>    &#125;);<br>&#125;<br><br><span class="hljs-keyword">let</span> a = [];<br>push(a, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);<br></code></pre></td></tr></table></figure>
<p>注意，rest 参数只能是最后一个参数，关于 rest 参数，可以参考 ES6 中的 rest 参数。</p>
</li>
<li><p>重载：</p>
<p>  重载允许一个函数接受不同数量或类型的参数时，作出不同的处理。</p>
<p>  比如，我们需要实现一个函数 reverse，输入数字 123 的时候，输出反转的数字 321，输入字符串 ‘hello’ 的时候，输出反转的字符串 ‘olleh’。</p>
<p>  利用联合类型，我们可以这么实现：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reverse</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span></span>): <span class="hljs-title">number</span> | <span class="hljs-title">string</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> x === <span class="hljs-string">&#x27;number&#x27;</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Number</span>(x.toString().split(<span class="hljs-string">&#x27;&#x27;</span>).reverse().join(<span class="hljs-string">&#x27;&#x27;</span>));<br>    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> x === <span class="hljs-string">&#x27;string&#x27;</span>) &#123;<br>        <span class="hljs-keyword">return</span> x.split(<span class="hljs-string">&#x27;&#x27;</span>).reverse().join(<span class="hljs-string">&#x27;&#x27;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>然而这样有一个缺点，就是不能够精确的表达，输入为数字的时候，输出也应该为数字，输入为字符串的时候，输出也应该为字符串。</p>
</li>
</ul>
<p>这时，我们可以使用重载定义多个 reverse 的函数类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reverse</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span></span>;<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reverse</span>(<span class="hljs-params">x: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reverse</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span></span>): <span class="hljs-title">number</span> | <span class="hljs-title">string</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> x === <span class="hljs-string">&#x27;number&#x27;</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Number</span>(x.toString().split(<span class="hljs-string">&#x27;&#x27;</span>).reverse().join(<span class="hljs-string">&#x27;&#x27;</span>));<br>    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> x === <span class="hljs-string">&#x27;string&#x27;</span>) &#123;<br>        <span class="hljs-keyword">return</span> x.split(<span class="hljs-string">&#x27;&#x27;</span>).reverse().join(<span class="hljs-string">&#x27;&#x27;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上例中，我们重复定义了多次函数 reverse，前几次都是函数定义，最后一次是函数实现。在编辑器的代码提示中，可以正确的看到前两个提示。</p>
<p>注意，TypeScript 会优先从最前面的函数定义开始匹配，所以多个函数定义如果有包含关系，需要优先把精确的定义写在前面。</p>
<h3 id="类型推断"><a href="#类型推断" class="headerlink" title="类型推断"></a>类型推断</h3><p>  以下代码虽然没有指定类型，但是会在编译的时候报错：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> myFavoriteNumber = <span class="hljs-string">&#x27;seven&#x27;</span>;<br>myFavoriteNumber = <span class="hljs-number">7</span>;<br><br><span class="hljs-comment">// index.ts(2,1): error TS2322: Type &#x27;number&#x27; is not assignable to type &#x27;string&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>事实上，它等价于：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> myFavoriteNumber: <span class="hljs-built_in">string</span> = <span class="hljs-string">&#x27;seven&#x27;</span>;<br>myFavoriteNumber = <span class="hljs-number">7</span>;<br><br><span class="hljs-comment">// index.ts(2,1): error TS2322: Type &#x27;number&#x27; is not assignable to type &#x27;string&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>TypeScript 会在没有明确的指定类型的时候推测出一个类型，这就是类型推论。</p>
<p>如果定义的时候没有赋值，不管之后有没有赋值，都会被推断成 any 类型而完全不被类型检查：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> myFavoriteNumber;<br>myFavoriteNumber = <span class="hljs-string">&#x27;seven&#x27;</span>;<br>myFavoriteNumber = <span class="hljs-number">7</span>;<br></code></pre></td></tr></table></figure>
<h3 id="类型断言"><a href="#类型断言" class="headerlink" title="类型断言"></a>类型断言</h3><p>  有时候你会遇到这样的情况，你会比TypeScript更了解某个值的详细信息。 通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。<br></p>
<p>通过类型断言这种方式可以告诉编译器，“相信我，我知道自己在干什么”。 类型断言好比其它语言里的类型转换，但是不进行特殊的数据检查和解构。 它没有运行时的影响，只是在编译阶段起作用。 TypeScript会假设你，程序员，已经进行了必须的检查。<br>类型断言有两种形式。 其一是“尖括号”语法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> someValue: <span class="hljs-built_in">any</span> = <span class="hljs-string">&quot;this is a string&quot;</span>;<br><br><span class="hljs-keyword">let</span> strLength: <span class="hljs-built_in">number</span> = (&lt;<span class="hljs-built_in">string</span>&gt;someValue).length;<br></code></pre></td></tr></table></figure>
<p>另一个为as语法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> someValue: <span class="hljs-built_in">any</span> = <span class="hljs-string">&quot;this is a string&quot;</span>;<br><br><span class="hljs-keyword">let</span> strLength: <span class="hljs-built_in">number</span> = (someValue <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>).length;<br></code></pre></td></tr></table></figure>
<p>两种形式是等价的。 至于使用哪个大多数情况下是凭个人喜好；然而，当你在TypeScript里使用JSX时，只有as语法断言是被允许的。</p>
<h3 id="联合类型"><a href="#联合类型" class="headerlink" title="联合类型"></a>联合类型</h3><p>联合类型（Union Types）表示取值可以为多种类型中的一种。</p>
<p>简单的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> myFavoriteNumber: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;<br>myFavoriteNumber = <span class="hljs-string">&#x27;seven&#x27;</span>;<br>myFavoriteNumber = <span class="hljs-number">7</span>;<br><span class="hljs-keyword">let</span> myFavoriteNumber: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;<br>myFavoriteNumber = <span class="hljs-literal">true</span>;<br><br><span class="hljs-comment">// index.ts(2,1): error TS2322: Type &#x27;boolean&#x27; is not assignable to type &#x27;string | number&#x27;.</span><br><span class="hljs-comment">//   Type &#x27;boolean&#x27; is not assignable to type &#x27;number&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>联合类型使用|分隔每个类型。</p>
<p>这里的 let myFavoriteNumber: string | number的含义是，允许myFavoriteNumber 的类型是 string 或者 number，但是不能是其他类型。</p>
<p>访问联合类型的属性或方法</p>
<p>当 TypeScript 不确定一个联合类型的变量到底是哪个类型的时候，我们只能访问此联合类型的所有类型里共有的属性或方法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getLength</span>(<span class="hljs-params">something: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> something.length;<br>&#125;<br><br><span class="hljs-comment">// index.ts(2,22): error TS2339: Property &#x27;length&#x27; does not exist on type &#x27;string | number&#x27;.</span><br><span class="hljs-comment">//   Property &#x27;length&#x27; does not exist on type &#x27;number&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>上例中，length 不是 string 和 number 的共有属性，所以会报错。</p>
<p>访问 string 和 number 的共有属性是没问题的：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getString</span>(<span class="hljs-params">something: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span></span>): <span class="hljs-title">string</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> something.toString();<br>&#125;<br></code></pre></td></tr></table></figure>
<p>联合类型的变量在被赋值的时候，会根据类型推论的规则推断出一个类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">let</span> myFavoriteNumber: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;<br>myFavoriteNumber = <span class="hljs-string">&#x27;seven&#x27;</span>;<br><span class="hljs-built_in">console</span>.log(myFavoriteNumber.length); <span class="hljs-comment">// 5</span><br>myFavoriteNumber = <span class="hljs-number">7</span>;<br><span class="hljs-built_in">console</span>.log(myFavoriteNumber.length); <span class="hljs-comment">// 编译时报错</span><br><br><span class="hljs-comment">// index.ts(5,30): error TS2339: Property &#x27;length&#x27; does not exist on type &#x27;number&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>上例中，第二行的 myFavoriteNumber 被推断成了 string，访问它的 length 属性不会报错。</p>
<p>而第四行的 myFavoriteNumber 被推断成了 number，访问它的 length 属性时就报错了。</p>
<h3 id="Null-和-Undefined"><a href="#Null-和-Undefined" class="headerlink" title="Null 和 Undefined"></a>Null 和 Undefined</h3><p> TypeScript里，undefined和null两者各自有自己的类型分别叫做undefined和null。 和void相似，它们的本身的类型用处不是很大：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// Not much else we can assign to these variables!</span><br><span class="hljs-keyword">let</span> u: <span class="hljs-literal">undefined</span> = <span class="hljs-literal">undefined</span>;<br><span class="hljs-keyword">let</span> n: <span class="hljs-literal">null</span> = <span class="hljs-literal">null</span>;<br></code></pre></td></tr></table></figure>
<p>默认情况下null和undefined是所有类型的子类型。 就是说你可以把null和undefined赋值给number类型的变量。<br>然而，当你指定了<strong>–strictNullChecks</strong>标记，null和undefined只能赋值给void和它们各自。 这能避免很多常见的问题。 也许在某处你想传入一个string或null或undefined，你可以使用联合类型string | null | undefined。</p>
<h3 id="Never"><a href="#Never" class="headerlink" title="Never"></a>Never</h3><p> never类型表示的是那些永不存在的值的类型。 例如，never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型； 变量也可能是never类型，当它们被永不为真的类型保护所约束时。</p>
<p>never类型是任何类型的子类型，也可以赋值给任何类型；然而，没有类型是never的子类型或可以赋值给never类型（除了never本身之外）。 即使any也不可以赋值给never。<br>下面是一些返回never类型的函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">error</span>(<span class="hljs-params">message: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">never</span> </span>&#123;<br>    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(message);<br>&#125;<br><br><span class="hljs-comment">// 推断的返回值类型为never</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fail</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> error(<span class="hljs-string">&quot;Something failed&quot;</span>);<br>&#125;<br><br><span class="hljs-comment">// 返回never的函数必须存在无法达到的终点</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">infiniteLoop</span>(<span class="hljs-params"></span>): <span class="hljs-title">never</span> </span>&#123;<br>    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h1 id="声明文件"><a href="#声明文件" class="headerlink" title="声明文件"></a>声明文件</h1><p> 当使用第三方库时，我们需要引用它的声明文件，才能获得对应的代码补全、接口提示等功能。</p>
<ul>
<li>declare var 声明全局变量</li>
<li>declare function 声明全局方法</li>
<li>declare class 声明全局类</li>
<li>declare enum 声明全局枚举类型</li>
<li>declare namespace 声明（含有子属性的）全局对象</li>
<li>interface 和 type 声明全局类型</li>
<li>export 导出变量</li>
<li>export namespace 导出（含有子属性的）对象</li>
<li>export default ES6 默认导出</li>
<li>export = commonjs 导出模块</li>
<li>export as namespace UMD 库声明全局变量</li>
<li>declare global 扩展全局变量</li>
<li>declare module 扩展模块<br>/// <reference /> 三斜线指令<h3 id="什么是声明语句"><a href="#什么是声明语句" class="headerlink" title="什么是声明语句"></a>什么是声明语句</h3></li>
<li>假如我们想使用第三方库 jQuery，一种常见的方式是在 html 中通过&lt;script&gt;标签引入 jQuery，然后就可以使用全局变量$或 jQuery 了。</li>
</ul>
<p>我们通常这样获取一个 id 是 foo 的元素：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript">$(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br><span class="hljs-comment">// or</span><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>但是在 ts 中，编译器并不知道 $或 jQuery 是什么东西1：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs javascript">jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br><span class="hljs-comment">// ERROR: Cannot find name &#x27;jQuery&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>这时，我们需要使用 declare var 来定义它的类型2：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">var</span> jQuery: <span class="hljs-function">(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">any</span>;<br><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>上例中，declare var 并没有真的定义一个变量，只是定义了全局变量 jQuery 的类型，仅仅会用于编译时的检查，在编译结果中会被删除。它编译结果是：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript">jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br></code></pre></td></tr></table></figure>
<h2 id="什么是声明文件"><a href="#什么是声明文件" class="headerlink" title="什么是声明文件"></a>什么是声明文件</h2><p>通常我们会把声明语句放到一个单独的文件<strong>（jQuery.d.ts）</strong>中，这就是声明文件3：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">var</span> jQuery: <span class="hljs-function">(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">any</span>;<br><span class="hljs-comment">// src/index.ts</span><br><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>声明文件必需以 .d.ts 为后缀。</p>
<p>一般来说，ts 会解析项目中所有的*.ts文件，当然也包含以.d.ts结尾的文件。所以当我们将jQuery.d.ts放到项目中时，其他所有 *.ts文件就都可以获得 jQuery 的类型定义了。</p>
<h2 id="书写声明文件"><a href="#书写声明文件" class="headerlink" title="书写声明文件"></a>书写声明文件</h2><p> 当一个第三方库没有提供声明文件时，我们就需要自己书写声明文件了。前面只介绍了最简单的声明文件内容，而真正书写一个声明文件并不是一件简单的事，以下会详细介绍如何书写声明文件。</p>
<p>在不同的场景下，声明文件的内容和使用方式会有所区别。</p>
<p>库的使用场景主要有以下几种：</p>
<ul>
<li>全局变量：通过&lt;script&gt;标签引入第三方库，注入全局变量</li>
<li>npm 包：通过import foo from ‘foo’导入，符合 ES6 模块规范</li>
<li>UMD 库：既可以通过&lt;script&gt;标签引入，又可以通过import导入</li>
<li>直接扩展全局变量：通过&lt;script&gt;标签引入后，改变一个全局变量的结构</li>
<li>在 npm 包或 UMD 库中扩展全局变量：引用 npm 包或 UMD 库后，改变一个全局变量的结构</li>
<li>模块插件：通过&lt;script&gt;或 import导入后，改变另一个模块的结构<h3 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h3><br>
 全局变量是最简单的一种场景，之前举的例子就是通过\<script\>标签引入 jQuery，注入全局变量 $和 jQuery。
 <br>
 <br>
使用全局变量的声明文件时，如果是以 npm install @types/xxx --save-dev安装的，则不需要任何配置。如果是将声明文件直接存放于当前项目中，则建议和其他源码一起放到 src 目录下（或者对应的源码目录下）：


</li>
</ul>
<p> <img src="https://img-blog.csdnimg.cn/20200624111613933.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" srcset="/blog/img/loading.gif" lazyload></p>
<p> 如果没有生效，可以检查下 tsconfig.json 中的 files、include 和 exclude 配置，确保其包含了 jQuery.d.ts 文件。</p>
<p> 全局变量的声明文件主要有以下几种语法：</p>
<ul>
<li>declare var 声明全局变量</li>
<li>declare function 声明全局方法</li>
<li>declare class 声明全局类</li>
<li>declare enum 声明全局枚举类型</li>
<li>declare namespace 声明（含有子属性的）全局对象</li>
<li>interface 和 type 声明全局类型<h3 id="declare-var-let-const"><a href="#declare-var-let-const" class="headerlink" title="declare var/let/const"></a>declare var/let/const</h3></li>
</ul>
<p>在所有的声明语句中，declare var 是最简单的，如之前所学，它能够用来定义一个全局变量的类型。与其类似的，还有 declare let 和 declare const，使用 let 与使用 var 没有什么区别：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">let</span> jQuery: <span class="hljs-function">(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">any</span>;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br><span class="hljs-comment">// 使用 declare let 定义的 jQuery 类型，允许修改这个全局变量</span><br>jQuery = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">selector</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">document</span>.querySelector(selector);<br>&#125;;<br></code></pre></td></tr></table></figure>
<p>而当我们使用 const 定义时，表示此时的全局变量是一个常量，不允许再去修改它的值了4：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">const</span> jQuery: <span class="hljs-function">(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">any</span>;<br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br><span class="hljs-comment">// 使用 declare const 定义的 jQuery 类型，禁止修改这个全局变量</span><br>jQuery = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">selector</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">document</span>.querySelector(selector);<br>&#125;;<br><span class="hljs-comment">// ERROR: Cannot assign to &#x27;jQuery&#x27; because it is a constant or a read-only property.</span><br></code></pre></td></tr></table></figure>
<p>一般来说，全局变量都是禁止修改的常量，所以大部分情况都应该使用 const 而不是 var 或 let。</p>
<p>需要注意的是，声明语句中只能定义类型，切勿在声明语句中定义具体的实现：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">const</span> jQuery = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">selector</span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">document</span>.querySelector(selector);<br>&#125;;<br><span class="hljs-comment">// ERROR: An implementation cannot be declared in ambient contexts.</span><br></code></pre></td></tr></table></figure>
<h3 id="declare-function"><a href="#declare-function" class="headerlink" title="declare function"></a>declare function</h3><p>declare function 用来定义全局函数的类型。jQuery 其实就是一个函数，所以也可以用 function 来定义：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">jQuery</span>(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span></span>;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>在函数类型的声明语句中，函数重载也是支持的：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">jQuery</span>(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span></span>;<br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">jQuery</span>(<span class="hljs-params">domReadyCallback: () =&gt; <span class="hljs-built_in">any</span></span>): <span class="hljs-title">any</span></span>;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br>jQuery(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>    alert(<span class="hljs-string">&#x27;Dom Ready!&#x27;</span>);<br>&#125;);<br></code></pre></td></tr></table></figure>
<h3 id="declare-class"><a href="#declare-class" class="headerlink" title="declare class"></a>declare class</h3><p>当全局变量是一个类的时候，我们用 declare class 来定义它的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/Animal.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    <span class="hljs-title">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>);<br>    sayHi(): <span class="hljs-built_in">string</span>;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">let</span> cat = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>同样的，declare class 语句也只能用来定义类型，不能用来定义具体的实现，比如定义 sayHi 方法的具体实现则会报错：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/Animal.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    name: <span class="hljs-built_in">string</span>;<br>    <span class="hljs-title">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>);<br>    <span class="hljs-function"><span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span>`</span>;<br>    &#125;;<br>    <span class="hljs-comment">// ERROR: An implementation cannot be declared in ambient contexts.</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="declare-enum"><a href="#declare-enum" class="headerlink" title="declare enum"></a>declare enum</h3><p>使用 declare enum 定义的枚举类型也称作外部枚举（Ambient Enums），举例如下：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/Directions.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">let</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>
<p>与其他全局变量的类型声明一致，declare enum 仅用来定义类型，而不是具体的值。</p>
<p>Directions.d.ts 仅仅会用于编译时的检查，声明文件里的内容在编译结果中会被删除。它编译结果是：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">var</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>

<p>其中 Directions 是由第三方库定义好的全局变量。</p>
<h3 id="declare-namespace"><a href="#declare-namespace" class="headerlink" title="declare namespace"></a>declare namespace</h3><p>namespace 是 ts 早期时为了解决模块化而创造的关键字，中文称为命名空间。</p>
<p>由于历史遗留原因，在早期还没有 ES6 的时候，ts 提供了一种模块化方案，使用 module 关键字表示内部模块。但由于后来 ES6 也使用了 module 关键字，ts 为了兼容 ES6，使用 namespace 替代了自己的 module，更名为命名空间。</p>
<p>随着 ES6 的广泛应用，现在已经不建议再使用 ts 中的 namespace，而推荐使用 ES6 的模块化方案了，故我们不再需要学习 namespace 的使用了。</p>
<p>namespace 被淘汰了，但是在声明文件中，declare namespace 还是比较常用的，它用来表示全局变量是一个对象，包含很多子属性。</p>
<p>比如 jQuery 是一个全局变量，它是一个对象，提供了一个 jQuery.ajax 方法可以调用，那么我们就应该使用 declare namespace jQuery 来声明这个拥有多个子属性的全局变量。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery.ajax(<span class="hljs-string">&#x27;/api/get_something&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>注意，在 declare namespace 内部，我们直接使用 function ajax 来声明函数，而不是使用 declare function ajax。类似的，也可以使用 const, class, enum 等语句：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>    <span class="hljs-keyword">const</span> version: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Event</span> </span>&#123;<br>        blur(eventType: EventType): <span class="hljs-built_in">void</span><br>    &#125;<br>    <span class="hljs-built_in">enum</span> EventType &#123;<br>        CustomClick<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery.ajax(<span class="hljs-string">&#x27;/api/get_something&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(jQuery.version);<br><span class="hljs-keyword">const</span> e = <span class="hljs-keyword">new</span> jQuery.Event();<br>e.blur(jQuery.EventType.CustomClick);<br></code></pre></td></tr></table></figure>
<p>嵌套的命名空间：</p>
<p>如果对象拥有深层的层级，则需要用嵌套的 namespace 来声明深层的属性的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>    <span class="hljs-keyword">namespace</span> fn &#123;<br>        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">extend</span>(<span class="hljs-params"><span class="hljs-built_in">object</span>: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery.ajax(<span class="hljs-string">&#x27;/api/get_something&#x27;</span>);<br>jQuery.fn.extend(&#123;<br>    check: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.each(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>            <span class="hljs-built_in">this</span>.checked = <span class="hljs-literal">true</span>;<br>        &#125;);<br>    &#125;<br>&#125;);<br></code></pre></td></tr></table></figure>
<p>假如 jQuery 下仅有 fn 这一个属性（没有 ajax 等其他属性或方法），则可以不需要嵌套 namespace11：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery.fn &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">extend</span>(<span class="hljs-params"><span class="hljs-built_in">object</span>: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery.fn.extend(&#123;<br>    check: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.each(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;<br>            <span class="hljs-built_in">this</span>.checked = <span class="hljs-literal">true</span>;<br>        &#125;);<br>    &#125;<br>&#125;);<br></code></pre></td></tr></table></figure>
<h3 id="interface-和-type"><a href="#interface-和-type" class="headerlink" title="interface 和 type"></a>interface 和 type</h3><p>除了全局变量之外，可能有一些类型我们也希望能暴露出来。在类型声明文件中，我们可以直接使用 interface 或 type 来声明一个全局的接口或类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">interface</span> AjaxSettings &#123;<br>    method?: <span class="hljs-string">&#x27;GET&#x27;</span> | <span class="hljs-string">&#x27;POST&#x27;</span><br>    data?: <span class="hljs-built_in">any</span>;<br>&#125;<br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: AjaxSettings</span>): <span class="hljs-title">void</span></span>;<br>&#125;<br><span class="hljs-comment">//这样的话，在其他文件中也可以使用这个接口或类型了：</span><br><br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">let</span> settings: AjaxSettings = &#123;<br>    method: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>    data: &#123;<br>        name: <span class="hljs-string">&#x27;foo&#x27;</span><br>    &#125;<br>&#125;;<br>jQuery.ajax(<span class="hljs-string">&#x27;/api/post_something&#x27;</span>, settings);<br></code></pre></td></tr></table></figure>
<p>type 与 interface 类似，不再赘述。</p>
<h3 id="防止命名冲突"><a href="#防止命名冲突" class="headerlink" title="防止命名冲突"></a>防止命名冲突</h3><p>暴露在最外层的 interface 或 type 会作为全局类型作用于整个项目中，我们应该尽可能的减少全局变量或全局类型的数量。故最好将他们放到 namespace 下：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-keyword">interface</span> AjaxSettings &#123;<br>        method?: <span class="hljs-string">&#x27;GET&#x27;</span> | <span class="hljs-string">&#x27;POST&#x27;</span><br>        data?: <span class="hljs-built_in">any</span>;<br>    &#125;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: AjaxSettings</span>): <span class="hljs-title">void</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>注意，在使用这个 interface 的时候，也应该加上 jQuery 前缀：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/index.ts</span><br><br><span class="hljs-keyword">let</span> settings: jQuery.AjaxSettings = &#123;<br>    method: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>    data: &#123;<br>        name: <span class="hljs-string">&#x27;foo&#x27;</span><br>    &#125;<br>&#125;;<br>jQuery.ajax(<span class="hljs-string">&#x27;/api/post_something&#x27;</span>, settings);<br></code></pre></td></tr></table></figure>

<h3 id="声明合并"><a href="#声明合并" class="headerlink" title="声明合并"></a>声明合并</h3><p>假如 jQuery 既是一个函数，可以直接被调用 jQuery(’#foo’)，又是一个对象，拥有子属性 jQuery.ajax()（事实确实如此），那么我们可以组合多个声明语句，它们会不冲突的合并起来：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// src/jQuery.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">jQuery</span>(<span class="hljs-params">selector: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span></span>;<br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> jQuery &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span>, settings?: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">void</span></span>;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br>jQuery(<span class="hljs-string">&#x27;#foo&#x27;</span>);<br>jQuery.ajax(<span class="hljs-string">&#x27;/api/get_something&#x27;</span>);<br></code></pre></td></tr></table></figure>
<h3 id="npm包"><a href="#npm包" class="headerlink" title="npm包"></a>npm包</h3><p>一般我们通过 import foo from ‘foo’ 导入一个 npm 包，这是符合 ES6 模块规范的。</p>
<p>在我们尝试给一个 npm 包创建声明文件之前，需要先看看它的声明文件是否已经存在。一般来说，npm 包的声明文件可能存在于两个地方：</p>
<p>与该 npm 包绑定在一起。判断依据是 package.json 中有 types 字段，或者有一个 index.d.ts 声明文件。这种模式不需要额外安装其他包，是最为推荐的，所以以后我们自己创建 npm 包的时候，最好也将声明文件与 npm 包绑定在一起。<br>发布到 @types里。我们只需要尝试安装一下对应的@types包就知道是否存在该声明文件，安装命令是<label style="color:yellow">npm install @types/foo –save-dev。</label>这种模式一般是由于 npm 包的维护者没有提供声明文件，所以只能由其他人将声明文件发布到 @types 里了。<br>假如以上两种方式都没有找到对应的声明文件，那么我们就需要自己为它写声明文件了。由于是通过 import 语句导入的模块，所以声明文件存放的位置也有所约束，一般有两种方案：</p>
<p>创建一个<label style="color:yellow">node_modules/@types/foo/index.d.ts</label>文件，存放 foo 模块的声明文件。这种方式不需要额外的配置，但是 node_modules 目录不稳定，代码也没有被保存到仓库中，无法回溯版本，有不小心被删除的风险，故不太建议用这种方案，一般只用作临时测试。<br>创建一个 types 目录，专门用来管理自己写的声明文件，将 foo 的声明文件放到 types/foo/index.d.ts中。这种方式需要配置下 tsconfig.json 中的 paths 和 baseUrl 字段。<br>目录结构：<br><img src="https://img-blog.csdnimg.cn/20200624141712240.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" srcset="/blog/img/loading.gif" lazyload></p>
<p>tsconfig.json 内容：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs json">&#123;<br>    <span class="hljs-attr">&quot;compilerOptions&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;module&quot;</span>: <span class="hljs-string">&quot;commonjs&quot;</span>,<br>        <span class="hljs-attr">&quot;baseUrl&quot;</span>: <span class="hljs-string">&quot;./&quot;</span>,<br>        <span class="hljs-attr">&quot;paths&quot;</span>: &#123;<br>            <span class="hljs-attr">&quot;*&quot;</span>: [<span class="hljs-string">&quot;types/*&quot;</span>]<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>如此配置之后，通过 import 导入 foo 的时候，也会去 types 目录下寻找对应的模块的声明文件了。</p>
<p>注意 module 配置可以有很多种选项，不同的选项会影响模块的导入导出模式。这里我们使用了 commonjs 这个最常用的选项，后面的教程也都默认使用的这个选项。</p>
<p>不管采用了以上两种方式中的哪一种，我都强烈建议大家将书写好的声明文件（通过给第三方库发 pull request，或者直接提交到 @types 里）发布到开源社区中，享受了这么多社区的优秀的资源，就应该在力所能及的时候给出一些回馈。只有所有人都参与进来，才能让 ts 社区更加繁荣。</p>
<p>npm 包的声明文件主要有以下几种语法：</p>
<ul>
<li>export 导出变量</li>
<li>export namespace 导出（含有子属性的）对象</li>
<li>export default ES6 默认导出</li>
<li>export = commonjs 导出模块<h3 id="export"><a href="#export" class="headerlink" title="export"></a>export</h3>npm 包的声明文件与全局变量的声明文件有很大区别。在 npm 包的声明文件中，使用 declare 不再会声明一个全局变量，而只会在当前文件中声明一个局部变量。只有在声明文件中使用 export 导出，然后在使用方 import 导入后，才会应用到这些类型声明。</li>
</ul>
<p>export 的语法与普通的 ts 中的语法类似，区别仅在于声明文件中禁止定义具体的实现：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> name: <span class="hljs-built_in">string</span>;<br><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-title">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>);<br>    sayHi(): <span class="hljs-built_in">string</span>;<br>&#125;<br><span class="hljs-keyword">export</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> Options &#123;<br>    data: <span class="hljs-built_in">any</span>;<br>&#125;<br><span class="hljs-comment">//对应的导入和使用模块应该是这样：</span><br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">import</span> &#123; name, getName, Animal, Directions, Options &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo&#x27;</span>;<br><br><span class="hljs-built_in">console</span>.log(name);<br><span class="hljs-keyword">let</span> myName = getName();<br><span class="hljs-keyword">let</span> cat = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br><span class="hljs-keyword">let</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br><span class="hljs-keyword">let</span> options: Options = &#123;<br>    data: &#123;<br>        name: <span class="hljs-string">&#x27;foo&#x27;</span><br>    &#125;<br>&#125;;<br></code></pre></td></tr></table></figure>
<h3 id="混用-declare-和-export"><a href="#混用-declare-和-export" class="headerlink" title="混用 declare 和 export"></a>混用 declare 和 export</h3><p>我们也可以使用 declare 先声明多个变量，最后再用 export 一次性导出。上例的声明文件可以等价的改写为16：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">const</span> name: <span class="hljs-built_in">string</span>;<br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-keyword">declare</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-title">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>);<br>    sayHi(): <span class="hljs-built_in">string</span>;<br>&#125;<br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><span class="hljs-keyword">interface</span> Options &#123;<br>    data: <span class="hljs-built_in">any</span>;<br>&#125;<br><span class="hljs-keyword">export</span> &#123; name, getName, Animal, Directions, Options &#125;;<br><span class="hljs-comment">//注意，与全局变量的声明文件类似，interface 前是不需要 declare 的。</span><br></code></pre></td></tr></table></figure>
<h3 id="export-namespace"><a href="#export-namespace" class="headerlink" title="export namespace"></a>export namespace</h3><p>与 declare namespace 类似，export namespace 用来导出一个拥有子属性的对象：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">namespace</span> foo &#123;<br>    <span class="hljs-keyword">const</span> name: <span class="hljs-built_in">string</span>;<br>    <span class="hljs-keyword">namespace</span> bar &#123;<br>        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">import</span> &#123; foo &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo&#x27;</span>;<br><span class="hljs-built_in">console</span>.log(foo.name);<br>foo.bar.baz();<br></code></pre></td></tr></table></figure>
<h3 id="export-default"><a href="#export-default" class="headerlink" title="export default"></a>export default</h3><p>在 ES6 模块系统中，使用 export default 可以导出一个默认值，使用方可以用 import foo from ‘foo’ 而不是 import { foo } from ‘foo’ 来导入这个默认值。</p>
<p>在类型声明文件中，export default 用来导出默认值的类型18：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br><br><span class="hljs-comment">// src/index.ts</span><br><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo&#x27;</span>;<br>foo();<br></code></pre></td></tr></table></figure>
<blockquote>
<p>注意，只有 function、class 和 interface 可以直接默认导出，其他的变量需要先定义出来，再默认导出</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-built_in">enum</span> Directions &#123;<br><span class="hljs-comment">// ERROR: Expression expected.</span><br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上例中 export default enum 是错误的语法，需要使用 declare enum 定义出来，然后使用 export default 导出：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Directions;<br></code></pre></td></tr></table></figure>
<p>针对这种默认导出，我们一般会将导出语句放在整个声明文件的最前面：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Directions;<br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="export-1"><a href="#export-1" class="headerlink" title="export ="></a>export =</h3><p>在 commonjs 规范中，我们用以下方式来导出一个模块：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-built_in">module</span>.exports = foo;<br><span class="hljs-comment">// 单个导出</span><br><span class="hljs-built_in">exports</span>.bar = bar;<br></code></pre></td></tr></table></figure>
<p>在 ts 中，针对这种模块导出，有多种方式可以导入，第一种方式是 const … = require：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// 整体导入</span><br><span class="hljs-keyword">const</span> foo = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;foo&#x27;</span>);<br><span class="hljs-comment">// 单个导入</span><br><span class="hljs-keyword">const</span> bar = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;foo&#x27;</span>).bar;<br></code></pre></td></tr></table></figure>
<p>第二种方式是 import … from，注意针对整体导出，需要使用 import * as 来导入：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// 整体导入</span><br><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo&#x27;</span>;<br><span class="hljs-comment">// 单个导入</span><br><span class="hljs-keyword">import</span> &#123; bar &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo</span><br></code></pre></td></tr></table></figure>
<p>第三种方式是 import … require，这也是 ts 官方推荐的方式：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// 整体导入</span><br><span class="hljs-keyword">import</span> foo = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;foo&#x27;</span>);<br><span class="hljs-comment">// 单个导入</span><br><span class="hljs-keyword">import</span> bar = foo.bar;<br></code></pre></td></tr></table></figure>
<p>对于这种使用 commonjs 规范的库，假如要为它写类型声明文件的话，就需要使用到 export = 这种语法了：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> = foo;<br><span class="hljs-keyword">declare</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> foo &#123;<br>    <span class="hljs-keyword">const</span> bar: <span class="hljs-built_in">number</span>;<br></code></pre></td></tr></table></figure>
<p>需要注意的是，上例中使用了 export = 之后，就不能再单个导出 export { bar } 了。所以我们通过声明合并，使用 declare namespace foo 来将 bar 合并到 foo 里。</p>
<p>准确地讲，export = 不仅可以用在声明文件中，也可以用在普通的 ts 文件中。实际上，import … require 和 export = 都是 ts 为了兼容 AMD 规范和 commonjs 规范而创立的新语法，由于并不常用也不推荐使用，所以这里就不详细介绍了，感兴趣的可以看官方文档。</p>
<p>由于很多第三方库是 commonjs 规范的，所以声明文件也就不得不用到 export = 这种语法了。但是还是需要再强调下，相比与 export =，我们更推荐使用 ES6 标准的 export default 和 export。</p>
<h3 id="UMD库"><a href="#UMD库" class="headerlink" title="UMD库"></a>UMD库</h3><p>既可以通过&lt;script&gt;标签引入，又可以通过 import 导入的库，称为 UMD 库。相比于 npm 包的类型声明文件，我们需要额外声明一个全局变量，为了实现这种方式，ts 提供了一个新语法 export as namespace。</p>
<h3 id="export-as-namespace"><a href="#export-as-namespace" class="headerlink" title="export as namespace"></a>export as namespace</h3><p>一般使用 export as namespace 时，都是先有了 npm 包的声明文件，再基于它添加一条 export as namespace 语句，即可将声明好的一个变量声明为全局变量，举例如下22：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">as</span> <span class="hljs-keyword">namespace</span> foo;<br>export = foo;<br><br>declare function foo(): string;<br>declare <span class="hljs-keyword">namespace</span> foo &#123;<br>    <span class="hljs-keyword">const</span> bar: <span class="hljs-built_in">number</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>当然它也可以与 export default 一起使用：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">as</span> <span class="hljs-keyword">namespace</span> foo;<br>export default foo;<br><br>declare function foo(): string;<br>declare <span class="hljs-keyword">namespace</span> foo &#123;<br>    <span class="hljs-keyword">const</span> bar: <span class="hljs-built_in">number</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="直接扩展全局变量"><a href="#直接扩展全局变量" class="headerlink" title="直接扩展全局变量"></a>直接扩展全局变量</h3><p>有的第三方库扩展了一个全局变量，可是此全局变量的类型却没有相应的更新过来，就会导致 ts 编译错误，此时就需要扩展全局变量的类型。比如扩展 String 类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-keyword">interface</span> String &#123;<br>    prependHello(): <span class="hljs-built_in">string</span>;<br>&#125;<br><br><span class="hljs-string">&#x27;foo&#x27;</span>.prependHello();<br></code></pre></td></tr></table></figure>
<p>通过声明合并，使用 interface String 即可给 String 添加属性或方法。</p>
<p>也可以使用 declare namespace 给已有的命名空间添加类型声明：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/jquery-plugin/index.d.ts</span><br><br><span class="hljs-keyword">declare</span> <span class="hljs-keyword">namespace</span> JQuery &#123;<br>    <span class="hljs-keyword">interface</span> CustomOptions &#123;<br>        bar: <span class="hljs-built_in">string</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">interface</span> JQueryStatic &#123;<br>    foo(options: JQuery.CustomOptions): <span class="hljs-built_in">string</span>;<br>&#125;<br><span class="hljs-comment">// src/index.ts</span><br><br>jQuery.foo(&#123;<br>    bar: <span class="hljs-string">&#x27;&#x27;</span><br>&#125;);<br></code></pre></td></tr></table></figure>
<h3 id="在NPM库或UMD库中扩展全局变量"><a href="#在NPM库或UMD库中扩展全局变量" class="headerlink" title="在NPM库或UMD库中扩展全局变量"></a>在NPM库或UMD库中扩展全局变量</h3><p>如之前所说，对于一个 npm 包或者 UMD 库的声明文件，只有 export 导出的类型声明才能被导入。所以对于 npm 包或 UMD 库，如果导入此库之后会扩展全局变量，则需要使用另一种语法在声明文件中扩展全局变量的类型，那就是 declare global。</p>
<h3 id="declare-global"><a href="#declare-global" class="headerlink" title="declare global"></a>declare global</h3><p>使用 declare global 可以在 npm 包或者 UMD 库的声明文件中扩展全局变量的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo/index.d.ts</span><br><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">global</span> &#123;<br>    <span class="hljs-keyword">interface</span> String &#123;<br>        prependHello(): <span class="hljs-built_in">string</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">export</span> &#123;&#125;;<br><span class="hljs-comment">// src/index.ts</span><br><br><span class="hljs-string">&#x27;bar&#x27;</span>.prependHello();<br></code></pre></td></tr></table></figure>
<p>注意即使此声明文件不需要导出任何东西，仍然需要导出一个空对象，用来告诉编译器这是一个模块的声明文件，而不是一个全局变量的声明文件。</p>
<h3 id="模块插件"><a href="#模块插件" class="headerlink" title="模块插件"></a>模块插件</h3><p>有时通过 import 导入一个模块插件，可以改变另一个原有模块的结构。此时如果原有模块已经有了类型声明文件，而插件模块没有类型声明文件，就会导致类型不完整，缺少插件部分的类型。ts 提供了一个语法 declare module，它可以用来扩展原有模块的类型。</p>
<h3 id="declare-module"><a href="#declare-module" class="headerlink" title="declare module"></a>declare module</h3><p>如果是需要扩展原有模块的话，需要在类型声明文件中先引用原有模块，再使用 declare module 扩展原有模块：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/moment-plugin/index.d.ts</span><br><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> moment <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;moment&#x27;</span>;<br><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">module</span> <span class="hljs-string">&#x27;moment&#x27;</span> &#123;<br>    <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>): <span class="hljs-title">moment</span>.<span class="hljs-title">CalendarKey</span></span>;<br>&#125;<br><span class="hljs-comment">// src/index.ts</span><br><br><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> moment <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;moment&#x27;</span>;<br><span class="hljs-keyword">import</span> <span class="hljs-string">&#x27;moment-plugin&#x27;</span>;<br><br>moment.foo();<br></code></pre></td></tr></table></figure>
<p>declare module 也可用于在一个文件中一次性声明多个模块的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs typescript"><span class="hljs-comment">// types/foo-bar.d.ts</span><br><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">module</span> <span class="hljs-string">&#x27;foo&#x27;</span> &#123;<br>    <span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> Foo &#123;<br>        foo: <span class="hljs-built_in">string</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">declare</span> <span class="hljs-built_in">module</span> <span class="hljs-string">&#x27;bar&#x27;</span> &#123;<br>    <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span></span>;<br>&#125;<br><span class="hljs-comment">// src/index.ts</span><br><br><span class="hljs-keyword">import</span> &#123; Foo &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;foo&#x27;</span>;<br><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> bar <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;bar&#x27;</span>;<br><br><span class="hljs-keyword">let</span> f: Foo;<br>bar.bar();<br></code></pre></td></tr></table></figure>
<h3 id="声明文件中的依赖"><a href="#声明文件中的依赖" class="headerlink" title="声明文件中的依赖"></a>声明文件中的依赖</h3><p>一个声明文件有时会依赖另一个声明文件中的类型，比如在前面的 declare module 的例子中，我们就在声明文件中导入了 moment，并且使用了 moment.CalendarKey 这个类型：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// types/moment-plugin/index.d.ts</span><br><br><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> moment <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;moment&#x27;</span>;<br><br>declare <span class="hljs-built_in">module</span> <span class="hljs-string">&#x27;moment&#x27;</span> &#123;<br>    <span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>): <span class="hljs-title">moment</span>.<span class="hljs-title">CalendarKey</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>除了可以在声明文件中通过 import 导入另一个声明文件中的类型之外，还有一个语法也可以用来导入另一个声明文件，那就是三斜线指令。</p>
<h3 id="三斜线指令"><a href="#三斜线指令" class="headerlink" title="三斜线指令"></a>三斜线指令</h3><p>与 namespace 类似，三斜线指令也是 ts 在早期版本中为了描述模块之间的依赖关系而创造的语法。随着 ES6 的广泛应用，现在已经不建议再使用 ts 中的三斜线指令来声明模块之间的依赖关系了。</p>
<p> 但是在声明文件中，它还是有一定的用武之地。</p>
<p>类似于声明文件中的 import，它可以用来导入另一个声明文件。与 import 的区别是，当且仅当在以下几个场景下，我们才需要使用三斜线指令替代 import：</p>
<ul>
<li>当我们在书写一个全局变量的声明文件时</li>
<li>当我们需要依赖一个全局变量的声明文件时</li>
<li>书写一个全局变量的声明文件<br>这些场景听上去很拗口，但实际上很好理解——在全局变量的声明文件中，是不允许出现 import, export 关键字的。一旦出现了，那么他就会被视为一个 npm 包或 UMD 库，就不再是全局变量的声明文件了。故当我们在书写一个全局变量的声明文件时，如果需要引用另一个库的类型，那么就必须用三斜线指令了：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// types/jquery-plugin/index.d.ts</span><br><br><span class="hljs-comment">/// &lt;reference types=&quot;jquery&quot; /&gt;</span><br><br>declare <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params">options: JQuery.AjaxSettings</span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-comment">// src/index.ts</span><br><br>foo(&#123;&#125;);<br></code></pre></td></tr></table></figure>
三斜线指令的语法如上，///后面使用 xml 的格式添加了对 jquery 类型的依赖，这样就可以在声明文件中使用 JQuery.AjaxSettings 类型了。</li>
</ul>
<p>注意，三斜线指令必须放在文件的最顶端，三斜线指令的前面只允许出现单行或多行注释。</p>
<p>依赖一个全局变量的声明文件<br>在另一个场景下，当我们需要依赖一个全局变量的声明文件时，由于全局变量不支持通过 import 导入，当然也就必须使用三斜线指令来引入了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// types/node-plugin/index.d.ts</span><br><br><span class="hljs-comment">/// &lt;reference types=&quot;node&quot; /&gt;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params">p: NodeJS.Process</span>): <span class="hljs-title">string</span></span>;<br><span class="hljs-comment">// src/index.ts</span><br><br><span class="hljs-keyword">import</span> &#123; foo &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;node-plugin&#x27;</span>;<br><br>foo(<span class="hljs-built_in">global</span>.process);<br></code></pre></td></tr></table></figure>
<p>在上面的例子中，我们通过三斜线指引入了 node 的类型，然后在声明文件中使用了 NodeJS.Process 这个类型。最后在使用到 foo 的时候，传入了 node 中的全局变量 process。</p>
<p>由于引入的 node 中的类型都是全局变量的类型，它们是没有办法通过 import 来导入的，所以这种场景下也只能通过三斜线指令来引入了。</p>
<p>以上两种使用场景下，都是由于需要书写或需要依赖全局变量的声明文件，所以必须使用三斜线指令。在其他的一些不是必要使用三斜线指令的情况下，就都需要使用 import 来导入。</p>
<h3 id="拆分声明文件"><a href="#拆分声明文件" class="headerlink" title="拆分声明文件"></a>拆分声明文件</h3><p>当我们的全局变量的声明文件太大时，可以通过拆分为多个文件，然后在一个入口文件中将它们一一引入，来提高代码的可维护性。比如 jQuery 的声明文件就是这样的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// node_modules/@types/jquery/index.d.ts</span><br><br><span class="hljs-comment">/// &lt;reference types=&quot;sizzle&quot; /&gt;</span><br><span class="hljs-comment">/// &lt;reference path=&quot;JQueryStatic.d.ts&quot; /&gt;</span><br><span class="hljs-comment">/// &lt;reference path=&quot;JQuery.d.ts&quot; /&gt;</span><br><span class="hljs-comment">/// &lt;reference path=&quot;misc.d.ts&quot; /&gt;</span><br><span class="hljs-comment">/// &lt;reference path=&quot;legacy.d.ts&quot; /&gt;</span><br><br><span class="hljs-keyword">export</span> = jQuery;<br></code></pre></td></tr></table></figure>
<p>其中用到了 types 和 path 两种不同的指令。它们的区别是：types 用于声明对另一个库的依赖，而 path 用于声明对另一个文件的依赖。</p>
<p>上例中，sizzle 是与 jquery 平行的另一个库，所以需要使用 types=“sizzle” 来声明对它的依赖。而其他的三斜线指令就是将 jquery 的声明拆分到不同的文件中了，然后在这个入口文件中使用 path=“foo” 将它们一一引入。</p>
<h3 id="其他三斜线指令"><a href="#其他三斜线指令" class="headerlink" title="其他三斜线指令"></a>其他三斜线指令</h3><p>除了这两种三斜线指令之外，还有其他的三斜线指令，比如/// &lt;reference no-default-lib=”true”/&gt;, /// &lt;amd-module /&gt;等，但它们都是废弃的语法，故这里就不介绍了。</p>
<h3 id="自动生成声明文件"><a href="#自动生成声明文件" class="headerlink" title="自动生成声明文件"></a>自动生成声明文件</h3><p>如果库的源码本身就是由 ts 写的，那么在使用 tsc 脚本将 ts 编译为 js 的时候，添加 declaration 选项，就可以同时也生成 .d.ts 声明文件了。</p>
<p>我们可以在命令行中添加 –declaration（简写 -d），或者在 tsconfig.json 中添加 declaration 选项。这里以 tsconfig.json 为例：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs json">&#123;<br>    <span class="hljs-attr">&quot;compilerOptions&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;module&quot;</span>: <span class="hljs-string">&quot;commonjs&quot;</span>,<br>        <span class="hljs-attr">&quot;outDir&quot;</span>: <span class="hljs-string">&quot;lib&quot;</span>,<br>        <span class="hljs-attr">&quot;declaration&quot;</span>: <span class="hljs-literal">true</span>,<br>    &#125;<br>&#125;<br>````<br>上例中我们添加了 outDir 选项，将 ts 文件的编译结果输出到 lib 目录下，然后添加了 declaration 选项，设置为 true，表示将会由 ts 文件自动生成 .d.ts 声明文件，也会输出到 lib 目录下。<br><br>运行 tsc 之后，目录结构如下：<br><br>![](https://img-blog.csdnimg.cn/20200624155129508.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70)<br><br>在这个例子中，src 目录下有两个 ts 文件，分别是 src/index.ts 和 src/bar/index.ts，它们被编译到 lib 目录下的同时，也会生成对应的两个声明文件 lib/index.d.ts 和 lib/bar/index.d.ts。它们的内容分别是<br>```ts<br><span class="hljs-comment">// src/index.ts</span><br>export * from &#x27;./bar&#x27;;<br>export default function foo() &#123;<br>    return &#x27;foo&#x27;;<br>&#125;<br><br><span class="hljs-comment">// src/bar/index.ts</span><br>export function bar() &#123;<br>    return &#x27;bar&#x27;;<br>&#125;<br><br><span class="hljs-comment">// lib/index.d.ts</span><br>export * from &#x27;./bar&#x27;;<br>export default function foo(): string;<br><br><span class="hljs-comment">// lib/bar/index.d.ts</span><br>export declare function bar(): string;<br></code></pre></td></tr></table></figure>
<p>可见，自动生成的声明文件基本保持了源码的结构，而将具体实现去掉了，生成了对应的类型声明。</p>
<p>使用 tsc 自动生成声明文件时，每个 ts 文件都会对应一个 .d.ts 声明文件。这样的好处是，使用方不仅可以在使用 import foo from ‘foo’ 导入默认的模块时获得类型提示，还可以在使用 import bar from ‘foo/lib/bar’ 导入一个子模块时，也获得对应的类型提示。</p>
<p>除了 declaration 选项之外，还有几个选项也与自动生成声明文件有关，这里只简单列举出来，不做详细演示了：</p>
<ul>
<li><p>declarationDir 设置生成 .d.ts 文件的目录</p>
</li>
<li><p>declarationMap 对每个 .d.ts 文件，都生成对应的 .d.ts.map（sourcemap）文件</p>
</li>
<li><p>emitDeclarationOnly 仅生成 .d.ts 文件，不生成 .js 文件/</p>
<h1 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h1><h2 id="类型别名"><a href="#类型别名" class="headerlink" title="类型别名"></a>类型别名</h2><p>类型别名用来给一个类型起个新名字。</p>
<p>例子</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts">  <span class="hljs-keyword">type</span> Name = <span class="hljs-built_in">string</span>;<br><span class="hljs-keyword">type</span> NameResolver = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">string</span>;<br><span class="hljs-keyword">type</span> NameOrResolver = Name | NameResolver;<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params">n: NameOrResolver</span>): <span class="hljs-title">Name</span> </span>&#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> n === <span class="hljs-string">&#x27;string&#x27;</span>) &#123;<br>        <span class="hljs-keyword">return</span> n;<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-keyword">return</span> n();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上例中，我们使用 type 创建类型别名。</p>
</li>
</ul>
<p>类型别名常用于联合类型。</p>
<h3 id="字符串字面量类型"><a href="#字符串字面量类型" class="headerlink" title="字符串字面量类型"></a>字符串字面量类型</h3><p>字符串字面量类型用来约束取值只能是某几个字符串中的一个。</p>
<p>简单的例子</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">type</span> EventNames = <span class="hljs-string">&#x27;click&#x27;</span> | <span class="hljs-string">&#x27;scroll&#x27;</span> | <span class="hljs-string">&#x27;mousemove&#x27;</span>;<br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleEvent</span>(<span class="hljs-params">ele: Element, event: EventNames</span>) </span>&#123;<br>    <span class="hljs-comment">// do something</span><br>&#125;<br><br>handleEvent(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&#x27;hello&#x27;</span>), <span class="hljs-string">&#x27;scroll&#x27;</span>);  <span class="hljs-comment">// 没问题</span><br>handleEvent(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&#x27;world&#x27;</span>), <span class="hljs-string">&#x27;dblclick&#x27;</span>); <span class="hljs-comment">// 报错，event 不能为 &#x27;dblclick&#x27;</span><br><br><span class="hljs-comment">// index.ts(7,47): error TS2345: Argument of type &#x27;&quot;dblclick&quot;&#x27; is not assignable to parameter of type &#x27;EventNames&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>上例中，我们使用 type 定了一个字符串字面量类型 EventNames，它只能取三种字符串中的一种。</p>
<p>注意，类型别名与字符串字面量类型都是使用 type 进行定义</p>
<h2 id="元组"><a href="#元组" class="headerlink" title="元组"></a>元组</h2><p>数组合并了相同类型的对象，而元组（Tuple）合并了不同类型的对象。</p>
<p>元组起源于函数编程语言（如 F#），这些语言中会频繁使用元组。</p>
<p>简单的例子：<br>定义一对值分别为 string 和 number 的元组：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>] = [<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-number">25</span>];<br></code></pre></td></tr></table></figure>
<p>当赋值或访问一个已知索引的元素时，会得到正确的类型：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>tom[<span class="hljs-number">0</span>] = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br>tom[<span class="hljs-number">1</span>] = <span class="hljs-number">25</span>;<br><br>tom[<span class="hljs-number">0</span>].slice(<span class="hljs-number">1</span>);<br>tom[<span class="hljs-number">1</span>].toFixed(<span class="hljs-number">2</span>);<br></code></pre></td></tr></table></figure>
<p>也可以只赋值其中一项：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>tom[<span class="hljs-number">0</span>] = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br></code></pre></td></tr></table></figure>
<p>但是当直接对元组类型的变量进行初始化或者赋值的时候，需要提供所有元组类型中指定的项。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>tom = [<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-number">25</span>];<br><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>tom = [<span class="hljs-string">&#x27;Tom&#x27;</span>];<br><br><span class="hljs-comment">// Property &#x27;1&#x27; is missing in type &#x27;[string]&#x27; but required in type &#x27;[string, number]&#x27;.</span><br></code></pre></td></tr></table></figure>
<h3 id="越界的元素："><a href="#越界的元素：" class="headerlink" title="越界的元素："></a>越界的元素：</h3><p>当添加越界的元素时，它的类型会被限制为元组中每个类型的联合类型：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> tom: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>tom = [<span class="hljs-string">&#x27;Tom&#x27;</span>, <span class="hljs-number">25</span>];<br>tom.push(<span class="hljs-string">&#x27;male&#x27;</span>);<br>tom.push(<span class="hljs-literal">true</span>);<br><br><span class="hljs-comment">// Argument of type &#x27;true&#x27; is not assignable to parameter of type &#x27;string | number&#x27;.</span><br></code></pre></td></tr></table></figure>
<h2 id="枚举-1"><a href="#枚举-1" class="headerlink" title="枚举"></a>枚举</h2><p>枚举（Enum）类型用于取值被限定在一定范围内的场景，比如一周只能有七天，颜色限定为红绿蓝等。</p>
<p>简单的例子:<br>枚举使用 enum 关键字来定义：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun, Mon, Tue, Wed, Thu, Fri, Sat&#125;;<br></code></pre></td></tr></table></figure>
<p>枚举成员会被赋值为从 0 开始递增的数字，同时也会对枚举值到枚举名进行反向映射：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun, Mon, Tue, Wed, Thu, Fri, Sat&#125;;<br><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sun&quot;</span>] === <span class="hljs-number">0</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Mon&quot;</span>] === <span class="hljs-number">1</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Tue&quot;</span>] === <span class="hljs-number">2</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sat&quot;</span>] === <span class="hljs-number">6</span>); <span class="hljs-comment">// true</span><br><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">0</span>] === <span class="hljs-string">&quot;Sun&quot;</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">1</span>] === <span class="hljs-string">&quot;Mon&quot;</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">2</span>] === <span class="hljs-string">&quot;Tue&quot;</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">6</span>] === <span class="hljs-string">&quot;Sat&quot;</span>); <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>
<p>事实上，上面的例子会被编译为：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> Days;<br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Days</span>) </span>&#123;<br>    Days[Days[<span class="hljs-string">&quot;Sun&quot;</span>] = <span class="hljs-number">0</span>] = <span class="hljs-string">&quot;Sun&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Mon&quot;</span>] = <span class="hljs-number">1</span>] = <span class="hljs-string">&quot;Mon&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Tue&quot;</span>] = <span class="hljs-number">2</span>] = <span class="hljs-string">&quot;Tue&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Wed&quot;</span>] = <span class="hljs-number">3</span>] = <span class="hljs-string">&quot;Wed&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Thu&quot;</span>] = <span class="hljs-number">4</span>] = <span class="hljs-string">&quot;Thu&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Fri&quot;</span>] = <span class="hljs-number">5</span>] = <span class="hljs-string">&quot;Fri&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Sat&quot;</span>] = <span class="hljs-number">6</span>] = <span class="hljs-string">&quot;Sat&quot;</span>;<br>&#125;)(Days || (Days = &#123;&#125;));<br></code></pre></td></tr></table></figure>
<p>我们也可以给枚举项手动赋值：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun = <span class="hljs-number">7</span>, Mon = <span class="hljs-number">1</span>, Tue, Wed, Thu, Fri, Sat&#125;;<br><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sun&quot;</span>] === <span class="hljs-number">7</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Mon&quot;</span>] === <span class="hljs-number">1</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Tue&quot;</span>] === <span class="hljs-number">2</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sat&quot;</span>] === <span class="hljs-number">6</span>); <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>
<p>上面的例子中，未手动赋值的枚举项会接着上一个枚举项递增。</p>
<p>如果未手动赋值的枚举项与手动赋值的重复了，TypeScript 是不会察觉到这一点的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun = <span class="hljs-number">3</span>, Mon = <span class="hljs-number">1</span>, Tue, Wed, Thu, Fri, Sat&#125;;<br><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sun&quot;</span>] === <span class="hljs-number">3</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Wed&quot;</span>] === <span class="hljs-number">3</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">3</span>] === <span class="hljs-string">&quot;Sun&quot;</span>); <span class="hljs-comment">// false</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-number">3</span>] === <span class="hljs-string">&quot;Wed&quot;</span>); <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>
<p>上面的例子中，递增到 3 的时候与前面的 Sun 的取值重复了，但是 TypeScript 并没有报错，导致 Days[3] 的值先是 “Sun”，而后又被 “Wed” 覆盖了。编译的结果是：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> Days;<br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Days</span>) </span>&#123;<br>    Days[Days[<span class="hljs-string">&quot;Sun&quot;</span>] = <span class="hljs-number">3</span>] = <span class="hljs-string">&quot;Sun&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Mon&quot;</span>] = <span class="hljs-number">1</span>] = <span class="hljs-string">&quot;Mon&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Tue&quot;</span>] = <span class="hljs-number">2</span>] = <span class="hljs-string">&quot;Tue&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Wed&quot;</span>] = <span class="hljs-number">3</span>] = <span class="hljs-string">&quot;Wed&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Thu&quot;</span>] = <span class="hljs-number">4</span>] = <span class="hljs-string">&quot;Thu&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Fri&quot;</span>] = <span class="hljs-number">5</span>] = <span class="hljs-string">&quot;Fri&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Sat&quot;</span>] = <span class="hljs-number">6</span>] = <span class="hljs-string">&quot;Sat&quot;</span>;<br>&#125;)(Days || (Days = &#123;&#125;));<br></code></pre></td></tr></table></figure>
<p>所以使用的时候需要注意，最好不要出现这种覆盖的情况。</p>
<p>手动赋值的枚举项可以不是数字，此时需要使用类型断言来让 tsc 无视类型检查 (编译出的 js 仍然是可用的)：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun = <span class="hljs-number">7</span>, Mon, Tue, Wed, Thu, Fri, Sat = &lt;<span class="hljs-built_in">any</span>&gt;<span class="hljs-string">&quot;S&quot;</span>&#125;;<br><span class="hljs-keyword">var</span> Days;<br>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Days</span>) </span>&#123;<br>    Days[Days[<span class="hljs-string">&quot;Sun&quot;</span>] = <span class="hljs-number">7</span>] = <span class="hljs-string">&quot;Sun&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Mon&quot;</span>] = <span class="hljs-number">8</span>] = <span class="hljs-string">&quot;Mon&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Tue&quot;</span>] = <span class="hljs-number">9</span>] = <span class="hljs-string">&quot;Tue&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Wed&quot;</span>] = <span class="hljs-number">10</span>] = <span class="hljs-string">&quot;Wed&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Thu&quot;</span>] = <span class="hljs-number">11</span>] = <span class="hljs-string">&quot;Thu&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Fri&quot;</span>] = <span class="hljs-number">12</span>] = <span class="hljs-string">&quot;Fri&quot;</span>;<br>    Days[Days[<span class="hljs-string">&quot;Sat&quot;</span>] = <span class="hljs-string">&quot;S&quot;</span>] = <span class="hljs-string">&quot;Sat&quot;</span>;<br>&#125;)(Days || (Days = &#123;&#125;));<br></code></pre></td></tr></table></figure>
<p>当然，手动赋值的枚举项也可以为小数或负数，此时后续未手动赋值的项的递增步长仍为 </p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Days &#123;Sun = <span class="hljs-number">7</span>, Mon = <span class="hljs-number">1.5</span>, Tue, Wed, Thu, Fri, Sat&#125;;<br><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sun&quot;</span>] === <span class="hljs-number">7</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Mon&quot;</span>] === <span class="hljs-number">1.5</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Tue&quot;</span>] === <span class="hljs-number">2.5</span>); <span class="hljs-comment">// true</span><br><span class="hljs-built_in">console</span>.log(Days[<span class="hljs-string">&quot;Sat&quot;</span>] === <span class="hljs-number">6.5</span>); <span class="hljs-comment">// true</span><br></code></pre></td></tr></table></figure>
<h3 id="常数项和计算所得项"><a href="#常数项和计算所得项" class="headerlink" title="常数项和计算所得项"></a>常数项和计算所得项</h3><p>枚举项有两种类型：常数项（constant member）和计算所得项（computed member）。</p>
<p>前面我们所举的例子都是常数项，一个典型的计算所得项的例子：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Color &#123;Red, Green, Blue = <span class="hljs-string">&quot;blue&quot;</span>.length&#125;;<br></code></pre></td></tr></table></figure>
<p>上面的例子中，“blue”.length 就是一个计算所得项。</p>
<p>上面的例子不会报错，但是如果紧接在计算所得项后面的是未手动赋值的项，那么它就会因为无法获得初始值而报错：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-built_in">enum</span> Color &#123;Red = <span class="hljs-string">&quot;red&quot;</span>.length, Green, Blue&#125;;<br><br><span class="hljs-comment">// index.ts(1,33): error TS1061: Enum member must have initializer.</span><br><span class="hljs-comment">// index.ts(1,40): error TS1061: Enum member must have initializer.</span><br></code></pre></td></tr></table></figure>
<p>下面是常数项和计算所得项的完整定义：</p>
<p>当满足以下条件时，枚举成员被当作是常数：</p>
<ul>
<li>不具有初始化函数并且之前的枚举成员是常数。在这种情况下，当前枚举成员的值为上一个枚举成员的值加 1。但第一个枚举元素是个例外。如果它没有初始化方法，那么它的初始值为 0。</li>
<li>枚举成员使用常数枚举表达式初始化。常数枚举表达式是 TypeScript 表达式的子集，它可以在编译阶段求值。当一个表达式满足下面条件之一时，它就是一个常数枚举表达式：<br>数字字面量</li>
<li>引用之前定义的常数枚举成员（可以是在不同的枚举类型中定义的）如果这个成员是在同一个枚举类型中定义的，可以使用非限定名来引用</li>
<li>带括号的常数枚举表达式</li>
<li>+, -, ~一元运算符应用于常数枚举表达式</li>
<li>+, -, *, /, %, &lt;&lt;, &gt;&gt;, &gt;&gt;&gt;, &amp;, |, ^二元运算符，常数枚举表达式做为其一个操作对象。若常数枚举表达式求值后为 NaN 或 Infinity，则会在编译阶段报错<br>所有其它情况的枚举成员被当作是需要计算得出的值。</li>
</ul>
<h3 id="常数枚举"><a href="#常数枚举" class="headerlink" title="常数枚举"></a>常数枚举</h3><p>常数枚举是使用 const enum 定义的枚举类型：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">const</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><br><span class="hljs-keyword">let</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>
<p>常数枚举与普通枚举的区别是，它会在编译阶段被删除，并且不能包含计算成员。</p>
<p>上例的编译结果是：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> directions = [<span class="hljs-number">0</span> <span class="hljs-comment">/* Up */</span>, <span class="hljs-number">1</span> <span class="hljs-comment">/* Down */</span>, <span class="hljs-number">2</span> <span class="hljs-comment">/* Left */</span>, <span class="hljs-number">3</span> <span class="hljs-comment">/* Right */</span>];<br></code></pre></td></tr></table></figure>
<p>假如包含了计算成员，则会在编译阶段报错：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">const</span> <span class="hljs-built_in">enum</span> Color &#123;Red, Green, Blue = <span class="hljs-string">&quot;blue&quot;</span>.length&#125;;<br><br><span class="hljs-comment">// index.ts(1,38): error TS2474: In &#x27;const&#x27; enum declarations member initializer must be constant expression.</span><br></code></pre></td></tr></table></figure>
<h3 id="外部枚举"><a href="#外部枚举" class="headerlink" title="外部枚举"></a>外部枚举</h3><p>外部枚举（Ambient Enums）是使用 declare enum 定义的枚举类型：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">declare</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><br><span class="hljs-keyword">let</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>
<p>之前提到过，declare 定义的类型只会用于编译时的检查，编译结果中会被删除。</p>
<p>上例的编译结果是：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>
<p>外部枚举与声明语句一样，常出现在声明文件中。</p>
<p>同时使用 declare 和 const 也是可以的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">const</span> <span class="hljs-built_in">enum</span> Directions &#123;<br>    Up,<br>    Down,<br>    Left,<br>    Right<br>&#125;<br><br><span class="hljs-keyword">let</span> directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];<br></code></pre></td></tr></table></figure>
<p>编译结果：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> directions = [<span class="hljs-number">0</span> <span class="hljs-comment">/* Up */</span>, <span class="hljs-number">1</span> <span class="hljs-comment">/* Down */</span>, <span class="hljs-number">2</span> <span class="hljs-comment">/* Left */</span>, <span class="hljs-number">3</span> <span class="hljs-comment">/* Right */</span>];<br></code></pre></td></tr></table></figure>
<p>TypeScript 的枚举类型的概念来源于 C#。</p>
<h2 id="类"><a href="#类" class="headerlink" title="类"></a>类</h2><p>传统方法中，JavaScript 通过构造函数实现类的概念，通过原型链实现继承。而在 ES6 中，我们终于迎来了 class。</p>
<p>TypeScript 除了实现了所有 ES6 中的类的功能以外，还添加了一些新的用法。</p>
<p>这一节主要介绍类的用法，下一节再介绍如何定义类的类型。</p>
<p>类的概念<br>虽然 JavaScript 中有类的概念，但是可能大多数 JavaScript 程序员并不是非常熟悉类，这里对类相关的概念做一个简单的介绍。</p>
<ul>
<li>类（Class）：定义了一件事物的抽象特点，包含它的属性和方法</li>
<li>对象（Object）：类的实例，通过 new 生成</li>
<li>面向对象（OOP）的三大特性：封装、继承、多态</li>
<li>封装（Encapsulation）：将对数据的操作细节隐藏起来，只暴露对外的接口。外界调用端不需要（也不可能）知道细节，就能通过对外提供的接口来访问该对象，同时也保证了外界无法任意更改对象内部的数据</li>
<li>继承（Inheritance）：子类继承父类，子类除了拥有父类的所有特性外，还有一些更具体的特性</li>
<li>多态（Polymorphism）：由继承而产生了相关的不同的类，对同一个方法可以有不同的响应。比如 Cat 和 Dog 都继承自 Animal，但是分别实现了自己的 eat 方法。此时针对某一个实例，我们无需了解它是 Cat 还是 Dog，就可以直接调用 eat 方法，程序会自动判断出来应该如何执行 eat</li>
<li>存取器（getter &amp; setter）：用以改变属性的读取和赋值行为</li>
<li>修饰符（Modifiers）：修饰符是一些关键字，用于限定成员或类型的性质。比如 public 表示公有属性或方法</li>
<li>抽象类（Abstract Class）：抽象类是供其他类继承的基类，抽象类不允许被实例化。- 抽象类中的抽象方法必须在子类中被实现</li>
<li>接口（Interfaces）：不同类之间公有的属性或方法，可以抽象成一个接口。接口可以被类实现（implements）。一个类只能继承自另一个类，但是可以实现多个接口<br>ES6 中类的用法<br>下面我们先回顾一下 ES6 中类的用法。</li>
</ul>
<h3 id="属性和方法"><a href="#属性和方法" class="headerlink" title="属性和方法"></a>属性和方法</h3><p>使用 class 定义类，使用 constructor 定义构造函数。</p>
<p>通过 new 生成新实例的时候，会自动调用构造函数。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> name;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.name = name;<br>    &#125;<br>    <span class="hljs-function"><span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span>`</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.sayHi()); <span class="hljs-comment">// My name is Jack</span><br></code></pre></td></tr></table></figure>
<h3 id="类的继承"><a href="#类的继承" class="headerlink" title="类的继承"></a>类的继承</h3><p>使用 extends 关键字实现继承，子类中使用 super 关键字来调用父类的构造函数和方法。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">super</span>(name); <span class="hljs-comment">// 调用父类的 constructor(name)</span><br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);<br>  &#125;<br>  <span class="hljs-function"><span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>)</span> &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&#x27;Meow, &#x27;</span> + <span class="hljs-built_in">super</span>.sayHi(); <span class="hljs-comment">// 调用父类的 sayHi()</span><br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> c = <span class="hljs-keyword">new</span> Cat(<span class="hljs-string">&#x27;Tom&#x27;</span>); <span class="hljs-comment">// Tom</span><br><span class="hljs-built_in">console</span>.log(c.sayHi()); <span class="hljs-comment">// Meow, My name is Tom</span><br></code></pre></td></tr></table></figure>
<h3 id="存取器"><a href="#存取器" class="headerlink" title="存取器"></a>存取器</h3><p>使用 getter 和 setter 可以改变属性的赋值和读取行为：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&#x27;Jack&#x27;</span>;<br>  &#125;<br>  <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">value</span>) &#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;setter: &#x27;</span> + value);<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Kitty&#x27;</span>); <span class="hljs-comment">// setter: Kitty</span><br>a.name = <span class="hljs-string">&#x27;Tom&#x27;</span>; <span class="hljs-comment">// setter: Tom</span><br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Jack</span><br></code></pre></td></tr></table></figure>
<h3 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h3><p>使用 static 修饰符修饰的方法称为静态方法，它们不需要实例化，而是直接通过类来调用：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-title">isAnimal</span>(<span class="hljs-params">a</span>)</span> &#123;<br>    <span class="hljs-keyword">return</span> a <span class="hljs-keyword">instanceof</span> Animal;<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br>Animal.isAnimal(a); <span class="hljs-comment">// true</span><br>a.isAnimal(a); <span class="hljs-comment">// TypeError: a.isAnimal is not a function</span><br></code></pre></td></tr></table></figure>
<h3 id="ES7-中类的用法"><a href="#ES7-中类的用法" class="headerlink" title="ES7 中类的用法"></a>ES7 中类的用法</h3><p>ES7 中有一些关于类的提案，TypeScript 也实现了它们，这里做一个简单的介绍。</p>
<h3 id="实例属性"><a href="#实例属性" class="headerlink" title="实例属性"></a>实例属性</h3><p>ES6 中实例的属性只能通过构造函数中的 this.xxx 来定义，ES7 提案中可以直接在类里面定义：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  name = <span class="hljs-string">&#x27;Jack&#x27;</span>;<br><br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params"></span>)</span> &#123;<br>    <span class="hljs-comment">// ...</span><br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal();<br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Jack</span><br></code></pre></td></tr></table></figure>
<h3 id="静态属性"><a href="#静态属性" class="headerlink" title="静态属性"></a>静态属性</h3><p>ES7 提案中，可以使用 static 定义一个静态属性：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">static</span> num = <span class="hljs-number">42</span>;<br><br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params"></span>)</span> &#123;<br>    <span class="hljs-comment">// ...</span><br>  &#125;<br>&#125;<br><br><span class="hljs-built_in">console</span>.log(Animal.num); <span class="hljs-comment">// 42</span><br></code></pre></td></tr></table></figure>
<h3 id="TypeScript-中类的用法"><a href="#TypeScript-中类的用法" class="headerlink" title="TypeScript 中类的用法"></a>TypeScript 中类的用法</h3><p>public private 和 protected</p>
<ul>
<li><p>TypeScript 可以使用三种访问修饰符（Access Modifiers），分别是 public、 private 和 protected。</p>
</li>
<li><p>public 修饰的属性或方法是公有的，可以在任何地方被访问到，默认所有的属性和方法都是 public 的</p>
</li>
<li><p>private 修饰的属性或方法是私有的，不能在声明它的类的外部访问</p>
</li>
<li><p>protected 修饰的属性或方法是受保护的，它和 private 类似，区别是它在子类中也是允许被访问的<br>下面举一些例子：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Jack</span><br>a.name = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Tom</span><br></code></pre></td></tr></table></figure>
<p>上面的例子中，name 被设置为了 public，所以直接访问实例的 name 属性是允许的。</p>
</li>
</ul>
<p>很多时候，我们希望有的属性是无法直接存取的，这时候就可以用 private 了：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">private</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Jack</span><br>a.name = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><br><span class="hljs-comment">// index.ts(9,13): error TS2341: Property &#x27;name&#x27; is private and only accessible within class &#x27;Animal&#x27;.</span><br><span class="hljs-comment">// index.ts(10,1): error TS2341: Property &#x27;name&#x27; is private and only accessible within class &#x27;Animal&#x27;.</span><br></code></pre></td></tr></table></figure>
<blockquote>
<p>需要注意的是，TypeScript 编译之后的代码中，并没有限制 private 属性在外部的可访问性。</p>
</blockquote>
<p>上面的例子编译后的代码是：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> Animal = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>&#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">return</span> Animal;<br>&#125;)();<br><span class="hljs-keyword">var</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.name);<br>a.name = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br></code></pre></td></tr></table></figure>
<p>使用 private 修饰的属性或方法，在子类中也是不允许访问的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">private</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">super</span>(name);<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);<br>  &#125;<br>&#125;<br><br><span class="hljs-comment">// index.ts(11,17): error TS2341: Property &#x27;name&#x27; is private and only accessible within class &#x27;Animal&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>而如果是用 protected 修饰，则允许在子类中访问：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">protected</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">super</span>(name);<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>当构造函数修饰为 private 时，该类不允许被继承或者实例化：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">super</span>(name);<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><br><span class="hljs-comment">// index.ts(7,19): TS2675: Cannot extend a class &#x27;Animal&#x27;. Class constructor is marked as private.</span><br><span class="hljs-comment">// index.ts(13,9): TS2673: Constructor of class &#x27;Animal&#x27; is private and only accessible within the class declaration.</span><br></code></pre></td></tr></table></figure>
<p>当构造函数修饰为 protected 时，该类只允许被继承：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">super</span>(name);<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><br><span class="hljs-comment">// index.ts(13,9): TS2674: Constructor of class &#x27;Animal&#x27; is protected and only accessible within the class declaration.</span><br></code></pre></td></tr></table></figure>
<p>参数属性<br>修饰符和readonly还可以使用在构造函数参数中，等同于类中定义该属性同时给该属性赋值，使代码更简洁。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-comment">// public name: string;</span><br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> name</span>)</span> &#123;<br>    <span class="hljs-comment">// this.name = name;</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="readonly"><a href="#readonly" class="headerlink" title="readonly"></a>readonly</h3><p>只读属性关键字，只允许出现在属性声明或索引签名或构造函数中。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">readonly</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.name); <span class="hljs-comment">// Jack</span><br>a.name = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><br><span class="hljs-comment">// index.ts(10,3): TS2540: Cannot assign to &#x27;name&#x27; because it is a read-only property.</span><br></code></pre></td></tr></table></figure>
<p>注意如果 readonly 和其他访问修饰符同时存在的话，需要写在其后面。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-comment">// public readonly name;</span><br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> name</span>)</span> &#123;<br>    <span class="hljs-comment">// this.name = name;</span><br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="抽象类"><a href="#抽象类" class="headerlink" title="抽象类"></a>抽象类</h3><p>abstract 用于定义抽象类和其中的抽象方法。</p>
<p> 什么是抽象类？</p>
<p>首先，抽象类是不允许被实例化的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> sayHi();<br>&#125;<br><br><span class="hljs-keyword">let</span> a = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><br><span class="hljs-comment">// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class &#x27;Animal&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>上面的例子中，我们定义了一个抽象类 Animal，并且定义了一个抽象方法 sayHi。在实例化抽象类的时候报错了。</p>
<p>其次，抽象类中的抽象方法必须被子类实现：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> sayHi();<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">eat</span>(<span class="hljs-params"></span>)</span> &#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span> is eating.`</span>);<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> cat = <span class="hljs-keyword">new</span> Cat(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br><br><span class="hljs-comment">// index.ts(9,7): error TS2515: Non-abstract class &#x27;Cat&#x27; does not implement inherited abstract member &#x27;sayHi&#x27; from class &#x27;Animal&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>上面的例子中，我们定义了一个类 Cat 继承了抽象类 Animal，但是没有实现抽象方法 sayHi，所以编译报错了。</p>
<p>下面是一个正确使用抽象类的例子：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> name;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name</span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> sayHi();<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>)</span> &#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Meow, My name is <span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span>`</span>);<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> cat = <span class="hljs-keyword">new</span> Cat(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure>
<p>上面的例子中，我们实现了抽象方法 sayHi，编译通过了。</p>
<p>需要注意的是，即使是抽象方法，TypeScript 的编译结果中，仍然会存在这个类，上面的代码的编译结果是：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> __extends =<br>  (<span class="hljs-built_in">this</span> &amp;&amp; <span class="hljs-built_in">this</span>.__extends) ||<br>  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">d, b</span>) </span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> p <span class="hljs-keyword">in</span> b) <span class="hljs-keyword">if</span> (b.hasOwnProperty(p)) d[p] = b[p];<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__</span>(<span class="hljs-params"></span>) </span>&#123;<br>      <span class="hljs-built_in">this</span>.constructor = d;<br>    &#125;<br>    d.prototype = b === <span class="hljs-literal">null</span> ? <span class="hljs-built_in">Object</span>.create(b) : ((__.prototype = b.prototype), <span class="hljs-keyword">new</span> __());<br>  &#125;;<br><span class="hljs-keyword">var</span> Animal = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>&#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  <span class="hljs-keyword">return</span> Animal;<br>&#125;)();<br><span class="hljs-keyword">var</span> Cat = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">_super</span>) </span>&#123;<br>  __extends(Cat, _super);<br>  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Cat</span>(<span class="hljs-params"></span>) </span>&#123;<br>    _super.apply(<span class="hljs-built_in">this</span>, <span class="hljs-built_in">arguments</span>);<br>  &#125;<br>  Cat.prototype.sayHi = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Meow, My name is &#x27;</span> + <span class="hljs-built_in">this</span>.name);<br>  &#125;;<br>  <span class="hljs-keyword">return</span> Cat;<br>&#125;)(Animal);<br><span class="hljs-keyword">var</span> cat = <span class="hljs-keyword">new</span> Cat(<span class="hljs-string">&#x27;Tom&#x27;</span>);<br></code></pre></td></tr></table></figure>
<h3 id="类的类型"><a href="#类的类型" class="headerlink" title="类的类型"></a>类的类型</h3><p>给类加上 TypeScript 的类型很简单，与接口类似：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>  name: <span class="hljs-built_in">string</span>;<br>  <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>)</span> &#123;<br>    <span class="hljs-built_in">this</span>.name = name;<br>  &#125;<br>  sayHi(): <span class="hljs-built_in">string</span> &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">$&#123;<span class="hljs-built_in">this</span>.name&#125;</span>`</span>;<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">let</span> a: Animal = <span class="hljs-keyword">new</span> Animal(<span class="hljs-string">&#x27;Jack&#x27;</span>);<br><span class="hljs-built_in">console</span>.log(a.sayHi()); <span class="hljs-comment">// My name is Jack</span><br></code></pre></td></tr></table></figure>
<p>12</p>
<h2 id="接口与类"><a href="#接口与类" class="headerlink" title="接口与类"></a>接口与类</h2><p>之前学习过，接口（Interfaces）可以用于对「对象的形状（Shape）」进行描述。</p>
<p>主要介绍接口的另一个用途，对类的一部分行为进行抽象。</p>
<h3 id="类实现接口"><a href="#类实现接口" class="headerlink" title="类实现接口"></a>类实现接口</h3><p>实现（implements）是面向对象中的一个重要概念。一般来讲，一个类只能继承自另一个类，有时候不同类之间可以有一些共有的特性，这时候就可以把特性提取成接口（interfaces），用 implements 关键字来实现。这个特性大大提高了面向对象的灵活性。</p>
<p>举例来说，门是一个类，防盗门是门的子类。如果防盗门有一个报警器的功能，我们可以简单的给防盗门添加一个报警方法。这时候如果有另一个类，车，也有报警器的功能，就可以考虑把报警器提取出来，作为一个接口，防盗门和车都去实现它：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> Alarm &#123;<br>    alert(): <span class="hljs-built_in">void</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Door</span> </span>&#123;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityDoor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Door</span> <span class="hljs-title">implements</span> <span class="hljs-title">Alarm</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-title">alert</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;SecurityDoor alert&#x27;</span>);<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-title">implements</span> <span class="hljs-title">Alarm</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-title">alert</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Car alert&#x27;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>一个类可以实现多个接口：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> Alarm &#123;<br>    alert(): <span class="hljs-built_in">void</span>;<br>&#125;<br><br><span class="hljs-keyword">interface</span> Light &#123;<br>    lightOn(): <span class="hljs-built_in">void</span>;<br>    lightOff(): <span class="hljs-built_in">void</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-title">implements</span> <span class="hljs-title">Alarm</span>, <span class="hljs-title">Light</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-title">alert</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Car alert&#x27;</span>);<br>    &#125;<br>    <span class="hljs-function"><span class="hljs-title">lightOn</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Car light on&#x27;</span>);<br>    &#125;<br>    <span class="hljs-function"><span class="hljs-title">lightOff</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Car light off&#x27;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上例中，Car 实现了 Alarm 和 Light 接口，既能报警，也能开关车灯。</p>
<h3 id="接口继承接口"><a href="#接口继承接口" class="headerlink" title="接口继承接口"></a>接口继承接口</h3><p>接口与接口之间可以是继承关系：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> Alarm &#123;<br>    alert(): <span class="hljs-built_in">void</span>;<br>&#125;<br><br><span class="hljs-keyword">interface</span> LightableAlarm <span class="hljs-keyword">extends</span> Alarm &#123;<br>    lightOn(): <span class="hljs-built_in">void</span>;<br>    lightOff(): <span class="hljs-built_in">void</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>这很好理解，LightableAlarm 继承了 Alarm，除了拥有 alert 方法之外，还拥有两个新方法 lightOn 和 lightOff。</p>
<h3 id="接口继承类"><a href="#接口继承类" class="headerlink" title="接口继承类"></a>接口继承类</h3><p>常见的面向对象语言中，接口是不能继承类的，但是在 TypeScript 中却是可以的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">interface</span> Point3d <span class="hljs-keyword">extends</span> Point &#123;<br>    z: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> point3d: Point3d = &#123;<span class="hljs-attr">x</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">z</span>: <span class="hljs-number">3</span>&#125;;<br></code></pre></td></tr></table></figure>
<p>为什么 TypeScript 会支持接口继承类呢？ </p>
<p>实际上，当我们在声明 class Point 时，除了会创建一个名为 Point 的类之外，同时也创建了一个名为 Point 的类型（实例的类型）。</p>
<p>所以我们既可以将 Point 当做一个类来用（使用 new Point 创建它的实例）：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);<br></code></pre></td></tr></table></figure>
<p>也可以将 Point 当做一个类型来用（使用 : Point 表示参数的类型）：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printPoint</span>(<span class="hljs-params">p: Point</span>) </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(p.x, p.y);<br>&#125;<br><br>printPoint(<span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));<br></code></pre></td></tr></table></figure>
<p>这个例子实际上可以等价于：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">interface</span> PointInstanceType &#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printPoint</span>(<span class="hljs-params">p: PointInstanceType</span>) </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(p.x, p.y);<br>&#125;<br><br>printPoint(<span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));<br></code></pre></td></tr></table></figure>
<p>上例中我们新声明的 PointInstanceType 类型，与声明 class Point 时创建的 Point 类型是等价的。</p>
<p>所以回到 Point3d 的例子中，我们就能很容易的理解为什么 TypeScript 会支持接口继承类了：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">interface</span> PointInstanceType &#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-comment">// 等价于 interface Point3d extends PointInstanceType</span><br><span class="hljs-keyword">interface</span> Point3d <span class="hljs-keyword">extends</span> Point &#123;<br>    z: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> point3d: Point3d = &#123;<span class="hljs-attr">x</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">z</span>: <span class="hljs-number">3</span>&#125;;<br></code></pre></td></tr></table></figure>
<p>当我们声明 interface Point3d extends Point 时，Point3d 继承的实际上是类 Point 的实例的类型。</p>
<p>换句话说，可以理解为定义了一个接口 Point3d 继承另一个接口 PointInstanceType。</p>
<p>所以「接口继承类」和「接口继承接口」没有什么本质的区别。</p>
<p>值得注意的是，PointInstanceType 相比于 Point，缺少了 constructor 方法，这是因为声明 Point 类时创建的 Point 类型是不包含构造函数的。另外，除了构造函数是不包含的，静态属性或静态方法也是不包含的（实例的类型当然不应该包括构造函数、静态属性或静态方法）。</p>
<p>换句话说，声明 Point 类时创建的 Point 类型只包含其中的实例属性和实例方法：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>&#123;<br>    <span class="hljs-comment">/** 静态属性，坐标系原点 */</span><br>    <span class="hljs-keyword">static</span> origin = <span class="hljs-keyword">new</span> Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);<br>    <span class="hljs-comment">/** 静态方法，计算与原点距离 */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-title">distanceToOrigin</span>(<span class="hljs-params">p: Point</span>)</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.sqrt(p.x * p.x + p.y * p.y);<br>    &#125;<br>    <span class="hljs-comment">/** 实例属性，x 轴的值 */</span><br>    x: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-comment">/** 实例属性，y 轴的值 */</span><br>    y: <span class="hljs-built_in">number</span>;<br>    <span class="hljs-comment">/** 构造函数 */</span><br>    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span></span>)</span> &#123;<br>        <span class="hljs-built_in">this</span>.x = x;<br>        <span class="hljs-built_in">this</span>.y = y;<br>    &#125;<br>    <span class="hljs-comment">/** 实例方法，打印此点 */</span><br>    <span class="hljs-function"><span class="hljs-title">printPoint</span>(<span class="hljs-params"></span>)</span> &#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.x, <span class="hljs-built_in">this</span>.y);<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">interface</span> PointInstanceType &#123;<br>    x: <span class="hljs-built_in">number</span>;<br>    y: <span class="hljs-built_in">number</span>;<br>    printPoint(): <span class="hljs-built_in">void</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> p1: Point;<br><span class="hljs-keyword">let</span> p2: PointInstanceType;<br></code></pre></td></tr></table></figure>
<p>上例中最后的类型 Point 和类型 PointInstanceType 是等价的。</p>
<p>同样的，在接口继承类的时候，也只会继承它的实例属性和实例方法。</p>
<h2 id="泛型"><a href="#泛型" class="headerlink" title="泛型"></a>泛型</h2><p>泛型（Generics）是指在定义函数、接口或类的时候，不预先指定具体的类型，而在使用的时候再指定类型的一种特性。</p>
<p>简单的例子<br>首先，我们来实现一个函数 createArray，它可以创建一个指定长度的数组，同时将每一项都填充一个默认值：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createArray</span>(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: <span class="hljs-built_in">any</span></span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">any</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br><br>createArray(<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;x&#x27;</span>); <span class="hljs-comment">// [&#x27;x&#x27;, &#x27;x&#x27;, &#x27;x&#x27;]</span><br></code></pre></td></tr></table></figure>
<p>上例中，我们使用了之前提到过的数组泛型来定义返回值的类型。</p>
<p>这段代码编译不会报错，但是一个显而易见的缺陷是，它并没有准确的定义返回值的类型：</p>
<p>Array&lt;any&gt;允许数组的每一项都为任意类型。但是我们预期的是，数组中每一项都应该是输入的 value 的类型。</p>
<p>这时候，泛型就派上用场了：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createArray</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: T</span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result: T[] = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br><br>createArray&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;x&#x27;</span>); <span class="hljs-comment">// [&#x27;x&#x27;, &#x27;x&#x27;, &#x27;x&#x27;]</span><br></code></pre></td></tr></table></figure>
<p>上例中，我们在函数名后添加了 <T>，其中 T 用来指代任意输入的类型，在后面的输入value: T和输出 Array<T>中即可使用了。</p>
<p>接着在调用的时候，可以指定它具体的类型为 string。当然，也可以不手动指定，而让类型推论自动推算出来：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createArray</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: T</span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result: T[] = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br><br>createArray(<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;x&#x27;</span>); <span class="hljs-comment">// [&#x27;x&#x27;, &#x27;x&#x27;, &#x27;x&#x27;]</span><br></code></pre></td></tr></table></figure>
<h3 id="多个类型参数"><a href="#多个类型参数" class="headerlink" title="多个类型参数"></a>多个类型参数</h3><p>定义泛型的时候，可以一次定义多个类型参数：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">swap</span>&lt;<span class="hljs-title">T</span>, <span class="hljs-title">U</span>&gt;(<span class="hljs-params">tuple: [T, U]</span>): [<span class="hljs-title">U</span>, <span class="hljs-title">T</span>] </span>&#123;<br>    <span class="hljs-keyword">return</span> [tuple[<span class="hljs-number">1</span>], tuple[<span class="hljs-number">0</span>]];<br>&#125;<br><br>swap([<span class="hljs-number">7</span>, <span class="hljs-string">&#x27;seven&#x27;</span>]); <span class="hljs-comment">// [&#x27;seven&#x27;, 7]</span><br></code></pre></td></tr></table></figure>
<p>上例中，我们定义了一个 swap 函数，用来交换输入的元组。</p>
<h3 id="泛型约束"><a href="#泛型约束" class="headerlink" title="泛型约束"></a>泛型约束</h3><p>在函数内部使用泛型变量的时候，由于事先不知道它是哪种类型，所以不能随意的操作它的属性或方法：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loggingIdentity</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">arg: T</span>): <span class="hljs-title">T</span> </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(arg.length);<br>    <span class="hljs-keyword">return</span> arg;<br>&#125;<br><br><span class="hljs-comment">// index.ts(2,19): error TS2339: Property &#x27;length&#x27; does not exist on type &#x27;T&#x27;.</span><br><span class="hljs-string">``</span><span class="hljs-string">`ts</span><br><span class="hljs-string">上例中，泛型 T 不一定包含属性 length，所以编译的时候报错了。</span><br><span class="hljs-string"></span><br><span class="hljs-string">这时，我们可以对泛型进行约束，只允许这个函数传入那些包含 length 属性的变量。这就是泛型约束：</span><br><span class="hljs-string">`</span><span class="hljs-string">``</span>ts<br><span class="hljs-keyword">interface</span> Lengthwise &#123;<br>    length: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loggingIdentity</span>&lt;<span class="hljs-title">T</span> <span class="hljs-title">extends</span> <span class="hljs-title">Lengthwise</span>&gt;(<span class="hljs-params">arg: T</span>): <span class="hljs-title">T</span> </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(arg.length);<br>    <span class="hljs-keyword">return</span> arg;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上例中，我们使用了 extends 约束了泛型 T 必须符合接口 Lengthwise 的形状，也就是必须包含 length 属性。</p>
<p>此时如果调用 loggingIdentity 的时候，传入的 arg 不包含 length，那么在编译阶段就会报错了：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> Lengthwise &#123;<br>    length: <span class="hljs-built_in">number</span>;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loggingIdentity</span>&lt;<span class="hljs-title">T</span> <span class="hljs-title">extends</span> <span class="hljs-title">Lengthwise</span>&gt;(<span class="hljs-params">arg: T</span>): <span class="hljs-title">T</span> </span>&#123;<br>    <span class="hljs-built_in">console</span>.log(arg.length);<br>    <span class="hljs-keyword">return</span> arg;<br>&#125;<br><br>loggingIdentity(<span class="hljs-number">7</span>);<br><br><span class="hljs-comment">// index.ts(10,17): error TS2345: Argument of type &#x27;7&#x27; is not assignable to parameter of type &#x27;Lengthwise&#x27;.</span><br></code></pre></td></tr></table></figure>
<p>多个类型参数之间也可以互相约束：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">copyFields</span>&lt;<span class="hljs-title">T</span> <span class="hljs-title">extends</span> <span class="hljs-title">U</span>, <span class="hljs-title">U</span>&gt;(<span class="hljs-params">target: T, source: U</span>): <span class="hljs-title">T</span> </span>&#123;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> id <span class="hljs-keyword">in</span> source) &#123;<br>        target[id] = (&lt;T&gt;source)[id];<br>    &#125;<br>    <span class="hljs-keyword">return</span> target;<br>&#125;<br><br><span class="hljs-keyword">let</span> x = &#123; <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span> &#125;;<br><br>copyFields(x, &#123; <span class="hljs-attr">b</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">20</span> &#125;);<br></code></pre></td></tr></table></figure>
<p>上例中，我们使用了两个类型参数，其中要求 T 继承 U，这样就保证了 U 上不会出现 T 中不存在的字段。</p>
<h3 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h3><p>之前学习过，可以使用接口的方式来定义一个函数需要符合的形状：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> SearchFunc &#123;<br>  (source: <span class="hljs-built_in">string</span>, <span class="hljs-attr">subString</span>: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">boolean</span>;<br>&#125;<br><br><span class="hljs-keyword">let</span> mySearch: SearchFunc;<br>mySearch = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">source: <span class="hljs-built_in">string</span>, subString: <span class="hljs-built_in">string</span></span>) </span>&#123;<br>    <span class="hljs-keyword">return</span> source.search(subString) !== -<span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>当然也可以使用含有泛型的接口来定义函数的形状：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> CreateArrayFunc &#123;<br>    &lt;T&gt;(length: <span class="hljs-built_in">number</span>, <span class="hljs-attr">value</span>: T): <span class="hljs-built_in">Array</span>&lt;T&gt;;<br>&#125;<br><br><span class="hljs-keyword">let</span> createArray: CreateArrayFunc;<br>createArray = <span class="hljs-function"><span class="hljs-keyword">function</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: T</span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result: T[] = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br><br>createArray(<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;x&#x27;</span>); <span class="hljs-comment">// [&#x27;x&#x27;, &#x27;x&#x27;, &#x27;x&#x27;]</span><br></code></pre></td></tr></table></figure>
<p>进一步，我们可以把泛型参数提前到接口名上：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> CreateArrayFunc&lt;T&gt; &#123;<br>    (length: <span class="hljs-built_in">number</span>, <span class="hljs-attr">value</span>: T): <span class="hljs-built_in">Array</span>&lt;T&gt;;<br>&#125;<br><br><span class="hljs-keyword">let</span> createArray: CreateArrayFunc&lt;<span class="hljs-built_in">any</span>&gt;;<br>createArray = <span class="hljs-function"><span class="hljs-keyword">function</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: T</span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result: T[] = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br><br>createArray(<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;x&#x27;</span>); <span class="hljs-comment">// [&#x27;x&#x27;, &#x27;x&#x27;, &#x27;x&#x27;]</span><br></code></pre></td></tr></table></figure>
<blockquote>
<p>注意，此时在使用泛型接口的时候，需要定义泛型的类型。</p>
</blockquote>
<h3 id="泛型类"><a href="#泛型类" class="headerlink" title="泛型类"></a>泛型类</h3><p>与泛型接口类似，泛型也可以用于类的类型定义中：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GenericNumber</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    zeroValue: T;<br>    add: <span class="hljs-function">(<span class="hljs-params">x: T, y: T</span>) =&gt;</span> T;<br>&#125;<br><br><span class="hljs-keyword">let</span> myGenericNumber = <span class="hljs-keyword">new</span> GenericNumber&lt;<span class="hljs-built_in">number</span>&gt;();<br>myGenericNumber.zeroValue = <span class="hljs-number">0</span>;<br>myGenericNumber.add = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x, y</span>) </span>&#123; <span class="hljs-keyword">return</span> x + y; &#125;;<br></code></pre></td></tr></table></figure>
<h3 id="泛型参数的默认类型"><a href="#泛型参数的默认类型" class="headerlink" title="泛型参数的默认类型"></a>泛型参数的默认类型</h3><p>在 TypeScript 2.3 以后，我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数，从实际值参数中也无法推测出时，这个默认类型就会起作用。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createArray</span>&lt;<span class="hljs-title">T</span> = <span class="hljs-title">string</span>&gt;(<span class="hljs-params">length: <span class="hljs-built_in">number</span>, value: T</span>): <span class="hljs-title">Array</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;<br>    <span class="hljs-keyword">let</span> result: T[] = [];<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; length; i++) &#123;<br>        result[i] = value;<br>    &#125;<br>    <span class="hljs-keyword">return</span> result;<br>&#125;<br></code></pre></td></tr></table></figure>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/typescript/">typescript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/%E5%AD%A6%E4%B9%A0/">学习</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2020/11/13/%E6%B7%B1%E5%85%A5Vue2%E6%95%B0%E6%8D%AE%E5%8A%AB%E6%8C%81/">
                        <span class="hidden-mobile">Vue2数据双向绑定</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
      <div class="col-lg-7 mx-auto nopadding-x-md">
        <div class="container custom mx-auto">
          <iframe frameborder="no" id="music" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=1397097038&auto=1&height=66"></iframe>
        </div>
      </div>
    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="#" target="_blank" rel="nofollow noopener"><span>Mike</span></a> <i class="iconfont icon-love"></i> <a href="#" target="_blank" rel="nofollow noopener"><span>Suansuan</span></a> <div class="powered-by"> <i class="fa fa-user-md"></i> </div> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        蜀ICP备2020033541号
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/blog/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/blog/local-search.xml";
      $('#local-search-input').on('click', function() {
        searchFunc(path, 'local-search-input', 'local-search-result');
      });
      $('#modalSearch').on('shown.bs.modal', function() {
        $('#local-search-input').focus();
      });
    })()
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/blog/js/boot.js" ></script>


</body>
</html>
